MVC - 模型具有相同的网页上的多个实体结合 [英] MVC - Model binding with multiple entities on the same page

查看:108
本文介绍了MVC - 模型具有相同的网页上的多个实体结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何使用型号在我从一个以上的实体在页面上返回信息的情况下绑定?

I am wondering how to use Model Binding in a scenario where I am returning information from more than one entity on a page?

我想从两个独立的实体,即客户+地址显示字段的组合。我使用微软的DAAB和定制业务实体为我的模型。

I want to display a combination of fields from two separate entities, ie Customer + Address. I am using Microsoft's DAAB and custom business entities for my model.

任何想法?

推荐答案

如果您要绑定到回传多种模式,你应该尽量使用绑定属性,并指定用于你的参数各型号的prefixes 。在某些情况下 - 在这里你可能无法使用独立的prefixes你的模型元素 - 你可能会发现这更容易做多TryUpdateModel和独立的白名单,而不是将模型中的参数

If you are trying to bind to multiple models on postback, you should try using the Bind attribute and specifying the prefixes used for each model in your arguments. In some scenarios -- where you may not be able to use separate prefixes for your model elements -- you might find this easier to do with multiple TryUpdateModel and separate whitelists rather than putting the models in the parameters.

public ActionResult Update( [Bind(Prefix="Customer")]Customer customer,
                            [Bind(Prefix="Address")]Address address )
{
   ...
}

这会假设你有一个视图模型,如:

This would assume you have a ViewModel like:

public class CustomerAddressModel
{
    public Customer Customer { get; set; }
    public Address Address { get; set; }
}

和引用它喜欢的:

<%= Html.TextBox( "Customer.Name" ) %>
...
<%= Html.TextBox( "Address.Street" ) %>

或者,使用TryUpdateModel,

or, using 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 ))
        {
            ...
        }
    }

}

在这种情况下,你的模型可能只包含来自两个不同的模型,你要更新的领域。

In this case, your model might contain just the fields from the two different models that you are trying to update.

public class CustomerAddressModel
{
    public string Name { get; set; }
    public string Company { get; set; }
    public string Street { get; set; }
    ...
}

这篇关于MVC - 模型具有相同的网页上的多个实体结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆