Tutorial :ASp.NET MVC: TryUpdateModel doesn't update all properties



Question:

I've got the following action:

public ActionResult Create()  {      var entity = new Employee();      TryUpdateModel(entity, new[] { "Person.Name", "Code", "CompanyID" });      if (ModelState.IsValid)      {          var result = Service.MergeEmployee(entity);          return RedirectToAction("List", new { success = true });      }      return View("Edit", new SupplierEmployeeModel() { Employee = entity });  }  

What happens is that the property "Person.Name" doesn't get filled by the TryUpdateModel.

This is my form:

 <fieldset>      <p>          <label for="Name"><%=Strings.NAME %></label>          <%= Html.TextBox("Person.Name", Model.Employee.Person.Name, new { Class = "text" })%>          <%= Html.ValidationMessage("Name", "*") %>      </p>      <p>          <label for="CompanyID"><%=Strings.SUPPLIER %></label>          <%= Html.DropDownList("CompanyID") %>          <%= Html.ValidationMessage("CompanyID", "*")%>      </p>      <p>          <label for="Code"><%=Strings.CODE %></label>          <%= Html.TextBox("Code", Model.Employee.Code)%>          <%= Html.ValidationMessage("Code", "*") %>      </p>      <p>          <%= Html.Hidden("ID", Model.Employee.ID)%>      </p>      <div id="tabs-DE-actions" class="ui-dialog-buttonpane  ui-helper-clearfix" style="display: block;">          <button class="ui-state-default ui-corner-all" type="submit"><%=Strings.SAVE%></button>      </div>  </fieldset>  

Any thoughts on why this is happening? Thanks


Solution:1

Make sure the Person object is initialized in the Employee constructor; if it's null to begin with it is probably not updated properly.

public Employee()  {      Person = new Person();  }  


Solution:2

Try this:

 TryUpdateModel(entity,"Person", new[] { "Name", "Code", "CompanyID" });  


Solution:3

In order to fill in Person.Name, the model binder has to create a new Person. Have you given the model binder enough info to do that? Alternately, try creating the Person yourself before binding.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »