简体   繁体   English

ASP.NET MVC - 表单和模型绑定器中的多个模型

[英]ASP.NET MVC - Multiple models in a form and model binders

I have a form which needs to populate 2 models. 我有一个表格需要填充2个模型。 Normally I use a ModelBinderAttribute on the forms post action ie 通常我在表单post post上使用ModelBinderAttribute,即

    [Authorize]
    [AcceptVerbs("POST")]
    public ActionResult Add([GigBinderAttribute]Gig gig, FormCollection formCollection)
    {
       ///Do stuff
    }

In my form, the fields are named the same as the models properties... 在我的表单中,字段的名称与模型属性相同...

However in this case I have 2 different models that need populating. 但是在这种情况下,我有2个不同的模型需要填充。

How do I do this? 我该怎么做呢? Any ideas? 有任何想法吗? Is it possible? 可能吗?

Actually... the best way is to do this: 实际上......最好的方法是这样做:

public ActionResult Add([GigBinderAttribute]Gig gig, [FileModelBinderAttribute]File file) {

} }

You CAN use multiple attributes! 您可以使用多个属性!

In cases like this, I tend to make a single model type to wrap up the various models involved: 在这种情况下,我倾向于使用单一模型类型来包含所涉及的各种模型:

class AddModel
{
     public Gig GigModel {get; set;}
     public OtherType OtherModel {get; set;}
}

...and bind that. ......并绑定它。

The UpdateModel or TryUpdateModel method can be used to do this. 可以使用UpdateModel或TryUpdateModel方法执行此操作。 You can pass through the model, the model you wish to bind, the prefix of the items you wish to bind to that model and the form. 您可以传递模型,要绑定的模型,要绑定到该模型的项的前缀和表单。 For example if your Item model has form variables of "Item.Value" then your update model method would be: 例如,如果您的Item模型具有“Item.Value”的表单变量,那么您的更新模型方法将是:

UpdateMode(modelObject, stringPrefix, formCollection);

If you're using the entity framework, it's worth pointing out that the UpdateModel method doesn't always work under some conditions. 如果您正在使用实体框架,那么值得指出的是UpdateModel方法在某些情况下并不总是有效。 It does work particularly well with POCOs though. 尽管如此,它确实对POCO有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM