In MVC3, the default is a data table that corresponds to a model, and a view that displays only one model.
But there are times when we might need to show multiple model content on a single view, that is, a Web page might show multiple tables of information, what if, then, ViewModel will be able to send the use.
ViewModel, as the name implies, is designed for the view service model, which is specifically prepared for view view.
I assume there are two tables, article and information tables, which need to be shown on the home page to see the following steps:
First, write two sheets of the corresponding model and the corresponding DbContext file, this step is relatively simple, I omitted.
Second, create a class (ViewModel), named Indexdata
public class Indexdata {public ienumerable<information> information {get; set;} Public ienumerable<article> article {get; set;} Public Indexdata () { Entities db = new entities (); This.information = Db.Information.ToList (); This. Article = db. Article.tolist (); } }
Third, controller controllers
Public ActionResult Index () { Indexdata ind = new Indexdata (); Return View (IND);
Four, view views
@model Indexdata
<div> <ul> @foreach (var item in Model.Information.Take (8)) { <li>@ Html.displayfor (M = Item. infotitle) </li> } </ul> </div> <div> <ul> @foreach (var item in Model.Article.Take (8)) { <li> @Html. displayfor (M = Item. articletitle) </li> } </ul></div>
If the article table wants to be divided into two parts, you can do this:
@model Indexdata
<div> <ul> @foreach (var item in Model.Article.Where (c=>c.type== "News"). Take (8)) { <li> @Html. displayfor (M = item.infotitle) </li> } </ul></div>
<div> <ul> @foreach (var item in Model.Article.Where (c=>c.type== "story"). Take (8)) { <li> @Html. displayfor (M = item.infotitle) </li> } </ul></div>
My viewmodel here only involves two tables, and in fact more sheets are the same. The first page of some portals may need to show more than 10 model, which is exactly the same.
Application of ViewModel in MVC3: One view displays multiple model