Access ViewModel fields in Edit view

476 views Asked by At

My Model:

public ECmain()
{
    this.Notes = new Collection<Notes>();
}

    public int ID { get; set; }
    public string Auth { get; set; }
    public string KeyWords { get; set; }
    public string Description { get; set; }
    public string URL { get; set; }
    public string Category { get; set; }
    public string SubCategory { get; set; }
    public string Title { get; set; }
    public string Live { get; set; }

    public virtual ICollection<Notes> Notes { get; set; }
    public virtual ICollection<Email> Email { get; set; }
}
public class MyViewModel
{
    public IQueryable<Notes> NotesList { get; set; }
    public IQueryable<ECmain> ECmainList { get; set; }
    public int ECmain.ID { get; set; }
    public IQueryable<Email> EmailList { get; set; }
}

My Controller:

// GET: ECmain/Edit/5
public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var viewModel = new MyViewModel
    {
        ECmainList = from m in db.ECmain.Take(10)
                     where m.ID ==  id
                     select m,
        NotesList = from n in db.Notes
                    where n.ECmainID ==id
                    select n,
        EmailList = from e in db.Email
                    where e.ECmainID ==id
                    select e
    };
    // viewModel.NotesList = new 

    if (viewModel == null)
    {
        return HttpNotFound();
    }
    return View(viewModel);
}

My Edit View:

@model EditSuite.Models.MyViewModel

@using (Html.BeginForm())
{
        @Html.HiddenFor(model => model.ID )

I want to access the ECmainList.ID The error is

Compiler Error Message: CS1061: 'EditSuite.Models.MyViewModel' does not contain a definition for 'ID'

I tried

@Html.HiddenFor(model => model.ECmainListID.ID ) 

and

@Html.HiddenFor(Model.model.ECmainListID.ID ) 

Neither one worked.

1

There are 1 answers

4
Erik Philips On

It seems pretty obvious from the compiler message:

Compiler Error Message: CS1061: 'EditSuite.Models.MyViewModel' does not contain a definition for 'ID'

So where on the following model is the ID?:

public class MyViewModel
{
  public IQueryable<Notes> NotesList { get; set; }
  public IQueryable<ECmain> ECmainList { get; set; }
  public IQueryable<Email> EmailList { get; set; }
  // there is no: public int ID { get; set; } ?
}

I want to access the ECmainList.ID

However, per your model the ECmainList is a IQueryable<ECmain> and the IQueryable<T> also does not have a public property or field called ID. How can you add an editor for a ID of a list of objects? You'd need to loop through the list and have multiple ID fields.