ASP.NET MVC - Multiple Models in Form and Insert Models

I have a form that should fill 2 models. I usually use the ModelBinderAttribute attribute for the post action of the ie form

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

In my form, the fields are called the same as the properties of the models ...

However, in this case, I have 2 different models that need to be filled.

How can I do it? Any ideas? Is it possible?

+6
asp.net-mvc
source share
3 answers

Actually ... the best way to do this:

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

}

You can use several attributes!

+9
source share

In such cases, I tend to make one type of model for wrapping the various models used:

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

... and tie it.

+8
source share

You can use the UpdateModel or TryUpdateModel methods for this. You can go through the model, the model you want to bind, the prefix of the elements you want to bind to this model and form. For example, if your item model has variables of the form "Item.Value", then your update model method will look like this:

 UpdateMode(modelObject, stringPrefix, formCollection); 

If you use an entity framework, it is worth noting that the UpdateModel method does not always work under certain conditions. However, it works very well with POCOs.

0
source share

All Articles