【问题标题】:Model with DropDownListFor SelectList not binding on the HttpPost具有 DropDownListFor SelectList 的模型未绑定到 HttpPost
【发布时间】: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


    【解决方案1】:

    您将使用 ViewBag 传递 DropdownList:

    ViewBag.SalutationList = new SelectList(db.SalutationTypes.Where(a => a.Active == true).ToList(), "Id", "Name");
    

    你必须在你的编辑视图中调用这个列表:

     @Html.DropDownList("SalutationList",String.Empty)
    

    【讨论】:

    • 为什么不在模型中?我看到了它作为复杂模型的一部分传入的示例。
    • 另外,这不会在 ViewModel 中的正确位置返回值。即model.Contact.SalutationType.Id
    【解决方案2】:

    问题在于,如果您使用不同的参数名称,DefaultModelBinder 将无法正确映射嵌套模型。您必须使用与模型名称相同的参数名称

    public ActionResult Edit(ContactManager contactManager)
    

    作为一般做法,始终使用模型名称作为参数名称以避免映射问题。

    进一步的建议:

    参数模型可以直接使用Contact,如果只需要联系人模型就不用ContactManager了。

    [HttpPost]
    public ActionResult Edit(Contact contact)
    {
        var test = contact.FirstName;
        return View();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多