Many mvc developers where asking on how to return multiple Models on a single view. Well its not that complex, and here is how I did it.
First : Create the models
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcProject.Models {
public class FirstModel : IEnumerable<FirstModel>, IList<FirstModel> {
public string Title { get; set; }
public string Message { get; set; }
...
}
public class SecondModel : IEnumerable<SecondModel>, IList<SecondModel> {
public string Title { get; set; }
public string Message { get; set; }
...
}
/*Strongly typed wrapper model*/
public class WrapperModel {
FirstModel firstModel;
SecondModel secondModel;
public WrapperModel() {
firstModel = new FirstModel();
secondModel = new SecondModel();
}
}
}
Second : Create our controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcProject.Models;
namespace MvcProject.Controllers {
public class HomeController : Controller {
public ActionResult Index() {
WrapperModel wrapperModel = new WrapperModel();
return View(wrapperModel);
}
}
}
Finally : Access our model through Razor
@model MvcProject.Models.WrapperModel
<div>
@{
foreach (MvcProject.Models.FirstModel fm in ViewData.Model.firstModel) {
<div>
<div id="SponsorNameContainer">@fm.Title</div>
<div id="SponsorMessageContainer">@fm.Message</div>
</div>
}
}
</div>
<div>
@{
foreach (MvcProject.Models.SecondModel sm in ViewData.Model.secondModel) {
<div>
<div id="SponsorNameContainer">@sm.Title</div>
<div id="SponsorMessageContainer">@sm.Message</div>
</div>
}
}
</div>
Advertisement

good Idea..
thanks
How you you go about editing multiple models related by a foreign key?
It’s not returning the mulitple model. it’s just returning one model that has two nested models
“not valid in the given context” error for
foreach (MvcProject.Models.FirstModel fm in ViewData.Model.firstModel) {
row.
Hi, very clean and simple solution… nice!! i will test right now.
…and this other article is very helpfull http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications
This seems to be not a working code. I am getting error while compiling. The error is ‘Multiplemodels.Models.FirstModel’ does not implement interface member ‘System.Collections.Generic.ICollection.Add(Multiplemodels.Models.FirstModel’). Also, in the View, I was not getting the below code:
foreach (MvcProject.Models.FirstModel fm in ViewData.Model.firstModel)
The ‘ViewData.Model.firstModel is having error, saying that it is inaccesible due to its protection level.
Any idea why it is going wrong?
Hi Rajamaran,
The first and second model must implement IEnumerable interface. The above code is incomplete but the concept is already there, notice the ellipses. If you want a full working source, i can send you a sample project just send me your email.