ViewModel在MVC3中的應用:一個view顯示多個model

來源:互聯網
上載者:User

標籤:簡單   display   nbsp   div   首頁   技術分享   控制器   tor   form   

在mvc3中,預設是一張資料表對應一個model,一個視圖 view只顯示一個model。

但是有些時候,我們一個視圖上可能需要顯示多個model的內容,即一個網頁可能要展示多張表的資訊,那怎麼辦呢,這時候,ViewModel就能派上用途了。

ViewModel,顧名思義,專為view服務的model,專門為view視圖準備的model。

我這裡假設有兩個張資料表,Article表和Information表,都需要在首頁上顯示出來,看看下面的步驟:

一、先寫出兩張表各自對應的model和相應的DbContext檔案,這一步比較簡單,我就省略了。

二、建立一個類(ViewModel),取名為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();        }    }

三、控制器Controller

    public ActionResult Index()        {            IndexData ind = new IndexData();            return View(ind);        }

四、view視圖

@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>

如果Article表又想分成兩部分來顯示,則可以這樣:

@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>
 

我這裡的ViewModel裡面只涉及到了兩張表,實際上更多張表也是一樣的。有些門戶網站的首頁,可能需要顯示十幾個model,做法完全是一樣的。

ViewModel在MVC3中的應用:一個view顯示多個model

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.