【发布时间】:2014-04-08 05:13:12
【问题描述】:
当我有以下代码并提交表单时,我的 post 操作将 Contact 对象显示为 null。如果我从视图中删除 DropDownListFor,则联系人对象包含预期的信息(名字)。为什么?如何让 SelectList 值起作用?
我的课:
public class ContactManager
{
public Contact Contact { get; set; }
public SelectList SalutationList { get; set; }
}
public class Contact
{
public int Id{get;set;}
public string FirstName{get; set;}
public SalutationType SalutationType{get; set;}
}
public class SalutationType
{
public int Id { get; set; }
public string Name { get; set; }
}
我的看法:
@model ViewModels.ContactManager
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Contact.Id)
@Html.DropDownListFor(model => model.Contact.SalutationType.Id, Model.SalutationList, "----", new { @class = "form-control" })
@Html.EditorFor(model => model.Contact.FirstName)
<input type="submit" value="Save" />
}
我的控制器:
public ActionResult Edit(int? id)
{
Contact contact = db.Contacts.FirstOrDefault(x => x.Id == id);
ContactManager cm = new ContactManager();
cm.Contact = contact;
cm.SalutationList = new SelectList(db.SalutationTypes.Where(a => a.Active == true).ToList(), "Id", "Name");
return View(cm);
}
[HttpPost]
public ActionResult Edit(ContactManger cm)
{
//cm at this point is null
var test = cm.Contact.FirstName;
return View();
}
【问题讨论】:
标签: asp.net-mvc linq-to-entities asp.net-mvc-5