有時需要在ASP.NET MVC4的視圖的@model中使用多個類型的實例,.NET Framework 4.0版本引入的System.Tuple類可以輕松滿足這個需求。
假設Person和Product是兩個類型,如下是控制器代碼。
- using System;
- using System.Web.Mvc;
- namespace Razor.Controllers
- {
- public class HomeController : Controller
- {
- Razor.Models.Product myProduct = new Models.Product { ProductID = 1, Name = "Book"};
- Razor.Models.Person myPerson = new Models.Person { PersonID = "1", Name = "Jack" };
- public ActionResult Index()
- {
- return View(Tuple.Create(myProduct,myPerson)); // 返回一個Tuple對象,Item1代表Product、Item2代表Person
- }
- }
- }
如下是視圖Index.cshtml的代碼
- @model Tuple<Razor.Models.Product, Razor.Models.Person>
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- <div>
- @Model.Item1.Name
- </div>
- </body>
- </html>
當然,還有許多其它的方法做到上述相同效果。但上述方法直接簡明,容易理解和使用。
有時候我們在頁面中會看見@model的語句,都是用於從后台向前端頁面傳遞數據的,下面我們來看看一個案例:
(1)定義Model實體
- public class SearchWithFundingList
- {
- /// <summary>
- /// 方案分類
- /// </summary>
- public int ProjectCategory { get; set; }
- /// <summary>
- /// 發起時間小
- /// </summary>
- public string MinAddDate { get; set; }
- /// <summary>
- /// 發起時間大
- /// </summary>
- public string MaxAddDate { get; set; }
- /// <summary>
- /// 狀態
- /// </summary>
- public int State { get; set; }
- /// <summary>
- /// 昵稱
- /// </summary>
- public string NickName { get; set; }
- /// <summary>
- /// 用戶id
- /// </summary>
- public int Mid { get; set; }
- }
(2)傳遞Model
- private SearchWithFundingList GetFormWithFundingNow(int id, int uid)
- {
- SearchWithFundingList model = new SearchWithFundingList();
- model.Mid = uid;
- model.State = WithFundingStateKey.Doing;
- model.ProjectCategory = id;
- return model;
- }
注意:一定要在最后return 實體,不然前台的Model實體是null
(3)具體調用
在頁面代碼最上面添加上實體的聲明
- @{Layout = null;}
- @model StockFunds.Entities.DTO.SearchWithFundingList
接下來就可以在頁面里使用Model(這里的實體就是指SearchWithFundingList實體),並且此時的Model已經是強類型了,我們可以點出具體的屬性,非常方便
- <span class="state">Model.State</span>元</span>
接下來是一個模擬用戶登錄的表單:
HomeController.cs

namespace Test.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View("~/Views/Home/Login.cshtml"); } public String Login(User user) { String name = user.Name; String password = user.Password; if ("張飛".Equals(name) && "abc".Equals(password)) { return "登錄成功"; } else { return "登錄失敗"; } } } }
Login.cshtml

@{ Layout = null; } @model Test.Models.User <html> <head> <title>用戶登錄</title> </head> <body> <div> <form action="Home/Login" method="post"> 用戶名:@Html.TextBoxFor(model=>model.Name)<br/> 密碼:@Html.TextBoxFor(model=>model.Password)<br /> <input type="submit" value="提交" /> </form> </div> </body> </html>