asp.net-mvc – UpdateModel前缀 – ASP.NET MVC

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – UpdateModel前缀 – ASP.NET MVC前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在TryUpdateModel()中遇到麻烦.我的表单字段用前缀命名,但我正在使用 – 作为我的分隔符,而不是默认点.
  1. <input type="text" id="Record-Title" name="Record-Title" />

当我尝试更新模型时,它不会被更新.如果我将name属性更改为Record.Title,它的工作原理完美,但这不是我想要做的.

  1. bool success = TryUpdateModel(record,"Record");

是否可以使用自定义分隔符?

解决方法

另外需要注意的是前缀是帮助反射找到正确的字段进行更新.例如,如果我有一个我的ViewData的自定义类,如:
  1. public class Customer
  2. {
  3. public string FirstName {get; set;}
  4. public string LastName {get; set;}
  5. }
  6.  
  7. public class MyCustomViewData
  8. {
  9. public Customer Customer {get; set;}
  10. public Address Address {get; set;}
  11. public string Comment {get; set;}
  12. }

我的页面上有一个文本框

  1. <%= Html.TextBox("FirstName",ViewData.Model.Customer.FirstName) %>

要么

  1. <%= Html.TextBox("Customer.FirstName",ViewData.Model.Customer.FirstName) %>

这是有用的

  1. public ActionResult Save (Formcollection form)
  2. {
  3. MyCustomViewData model = GetModel(); // get our model data
  4.  
  5. TryUpdateModel(model,form); // works for name="Customer.FirstName" only
  6. TryUpdateModel(model.Customer,form) // works for name="FirstName" only
  7. TryUpdateModel(model.Customer,"Customer",form); // works for name="Customer.FirstName" only
  8. TryUpdateModel(model,form) // do not work
  9.  
  10. ..snip..
  11. }

猜你在找的asp.Net相关文章