简体   繁体   中英

Model with DropDownListFor SelectList not binding on the HttpPost

When I have the following code and I submit the form my post action shows the Contact object as null. If I remove the DropDownListFor from the view the Contact object contains the expected information (FirstName). Why? How do I get the SelectList value to work?

My classes:

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

My view:

@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" />
}

My Controller:

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

You will pass the DropdownList using ViewBag:

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

than u have to call this list inside your edit view:

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

The problem is that the DefaultModelBinder won't be able to map nested models properly if you use a different parameter name. You must use the same parameter name as the model name.

public ActionResult Edit(ContactManager contactManager)

As a general practice, always use the name of the model as the parameter name to avoid mapping problems.

Further Suggestion:

You can just use Contact as the parameter model, no need to use ContactManager if you only need the contact model.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM