I am new to MVC3, I have an multiple models like BussinessDetails
,ContactPerson
,ServiceArea
,Address
and many more models. I have a single view page where shared view pages like Contacts
,BusinessDetails
,Address
,ServiceArea
etc.these are all in tabs. They have there own models.
My problem is that how to edit multiple models in a same edit view page. Before sending this post I take the help of the MVC3 "Music Store" example but there is only one model ALBUM
and they give edit operation for one model if there is one or more model how I shall edit in the same view page.
I have already made a parent business specification class. This is from MVC "Music Store"
public ActionResult Edit(int id) {
Album album = db.Albums.Find(id);
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
return View(album);
}
[HttpPost]
public ActionResult Edit(Album album) {
if (ModelState.IsValid) {
db.Entry(album).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
return View(album);
}
In HTTP POST
there is only on model ALBUM
if there is more models how i am perform edit operation on multiple models and view?
You'll need to create a View Model that contains both of the types that you need. Something like this (assuming you're editing both an Album and an Artist):
Then change your view to use the new model like so:
Then change your Get method to be something like:
Then change your Post method to take the
MyModel
type:Assuming your view has something like (wrapped in a form with a submit button of course):
You need to include the other ViewModels into a main
CompositeModel
like soSend that to your view like so
Modify your view to take the new model type
To refer to properties of the sub-models you can use syntax like this
or you can create a view in the
EditorTemplates
folder that takes a sub-model likeAlbumModel
and useEditorFor
like thisThe template would look something like this
Now just post
CompositeModel
back to your controller and then save all the sub-models and now Bob's your uncle!One alternative way is to use C# Tuples
http://www.dotnetperls.com/tuple
In your view and controller, define a tuple that is a list of your classes(models)