简体   繁体   中英

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

I have a form which needs to populate 2 models. Normally I use a ModelBinderAttribute on the forms post action ie

    [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.

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. 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:

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. It does work particularly well with POCOs though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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