在“编辑”视图中访问ViewModel字段

时间:2014-11-15 20:45:39

标签: asp.net-mvc asp.net-mvc-viewmodel

我的模特:

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; }
}

我的控制器:

// 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);
}

我的编辑视图:

@model EditSuite.Models.MyViewModel

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

我想访问ECmainList.ID错误是

  

编译器错误消息:CS1061:'EditSuite.Models.MyViewModel'不包含'ID'的定义

我试过

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

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

两个人都没有工作。

1 个答案:

答案 0 :(得分:0)

从编译器消息中可以看出很明显:

  

编译器错误消息:CS1061:&#39; EditSuite.Models.MyViewModel&#39;不包含&#39; ID&#39;

的定义

那么以下型号的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; } ?
}
  

我想访问ECmainList.ID

但是,根据您的模型,ECmainListIQueryable<ECmain>IQueryable<T>也没有名为ID的公共属性或字段。如何为对象列表的ID添加编辑器?您需要遍历列表并拥有多个ID字段。