2009-05-21 62 views
0

我已经得到了以下行动:ASp.NET MVC:TryUpdateModel不会更新所有属性

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

什么情况是,属性“Person.Name”没有得到由TryUpdateModel填补。

这是我的形式:

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

上为什么发生这种情况有什么想法? 感谢

回答

0

试试这个:

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

不幸的是,没有工作:(谢谢。 – 2009-05-21 11:28:57

0

为了填补Person.Name,模型绑定必须创建一个新的人。你有没有给模型绑定足够的信息做到这一点?或者,尝试在绑定前自己创建人员。

+0

奇怪的是,如果我不是使用tryupdatemode使用Employee类作为行动参数(公众的ActionResult创建(Employee实体)),它正确地结合,填写Person.Name。 – 2009-05-21 13:39:23

4

确保Person对象在Employee构造函数中初始化;如果开头为空,则可能未正确更新。

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