Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 i.e.

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

like image 556
iasksillyquestions Avatar asked Jan 18 '09 18:01

iasksillyquestions


People also ask

Can MVC have multiple models?

In MVC we cannot pass multiple models from a controller to the single view.

Can we have 2 models in a single view?

You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.

Can we bind multiple models with a single view?

Yes, you can use Tuple (brings magic in view having multiple model).


2 Answers

Actually... the best way is to do this:

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

}

You CAN use multiple attributes!

like image 176
iasksillyquestions Avatar answered Nov 09 '22 14:11

iasksillyquestions


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.

like image 36
Craig Stuntz Avatar answered Nov 09 '22 16:11

Craig Stuntz