ASp.NET MVC:TryUpdateModel不会更新所有属性

时间:2009-05-21 10:40:50

标签: asp.net-mvc modelbinder

我有以下行动:

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

TryUpdateModel不会填充属性“Person.Name”。

这是我的表格:

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

有关为何发生这种情况的任何想法? 感谢

3 个答案:

答案 0 :(得分:4)

确保在Employee构造函数中初始化Person对象;如果它开始时为null,则可能无法正确更新。

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

为了填写Person.Name,模型绑定器必须创建一个新的Person。你有足够的信息给模型粘合剂吗?或者,尝试在绑定之前自己创建Person。