我在TryUpdateModel()中遇到麻烦.我的表单字段用前缀命名,但我正在使用 – 作为我的分隔符,而不是默认点.
- <input type="text" id="Record-Title" name="Record-Title" />
当我尝试更新模型时,它不会被更新.如果我将name属性更改为Record.Title,它的工作原理完美,但这不是我想要做的.
- bool success = TryUpdateModel(record,"Record");
是否可以使用自定义分隔符?
解决方法
另外需要注意的是前缀是帮助反射找到正确的字段进行更新.例如,如果我有一个我的ViewData的自定义类,如:
- public class Customer
- {
- public string FirstName {get; set;}
- public string LastName {get; set;}
- }
- public class MyCustomViewData
- {
- public Customer Customer {get; set;}
- public Address Address {get; set;}
- public string Comment {get; set;}
- }
我的页面上有一个文本框
- <%= Html.TextBox("FirstName",ViewData.Model.Customer.FirstName) %>
要么
- <%= Html.TextBox("Customer.FirstName",ViewData.Model.Customer.FirstName) %>
这是有用的
- public ActionResult Save (Formcollection form)
- {
- MyCustomViewData model = GetModel(); // get our model data
- TryUpdateModel(model,form); // works for name="Customer.FirstName" only
- TryUpdateModel(model.Customer,form) // works for name="FirstName" only
- TryUpdateModel(model.Customer,"Customer",form); // works for name="Customer.FirstName" only
- TryUpdateModel(model,form) // do not work
- ..snip..
- }