如果您尝试在回发时绑定到多个模型,则应尝试使用 Bind 属性并在参数中指定用于每个模型的前缀。在某些情况下(您可能无法为模型元素使用单独的前缀),您可能会发现使用多个 TryUpdateModel 和单独的白名单更容易做到这一点,而不是将模型放入参数中。
public ActionResult Update( [Bind(Prefix="Customer")]Customer customer,
[Bind(Prefix="Address")]Address address )
{
...
}
这假设你有一个像这样的 ViewModel:
public class CustomerAddressModel
{
public Customer Customer { get; set; }
public Address Address { get; set; }
}
并像这样引用它:
<%= Html.TextBox( "Customer.Name" ) %>
...
<%= Html.TextBox( "Address.Street" ) %>
或者,使用 TryUpdateModel,
public ActionResult Update( int id )
{
var customer = db.Customers.Where( c => c.ID == id ).Single();
var whitelist = new string[] { "name", "company", ... };
if (TryUpdateModel( customer, whitelist ))
{
var addressWhitelist = new string[] { "street", "city", ... };
if (TryUpdateModel( customer.Address, addressWhitelist ))
{
...
}
}
}
在这种情况下,您的模型可能只包含您尝试更新的两个不同模型中的字段。
public class CustomerAddressModel
{
public string Name { get; set; }
public string Company { get; set; }
public string Street { get; set; }
...
}