ASP.NET MVC: TryUpdateModel does not update all properties

I have 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 });
}

      

It happens that the "Person.Name" property is not populated 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 to

0


a source to share


3 answers


Make sure the Person object is initialized in the Employee constructor; if it is zero to begin with, it is probably not updated correctly.



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

      

+4


a source


Try the following:



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

      

0


a source


To populate Person.Name, the model linker must create a new Person. Have you provided enough information about this device information? Alternatively, try creating the Person just before the binding.

0


a source







All Articles