ASP.NET MVC4中@model使用多個型別例項的方法
阿新 • • 發佈:2018-12-18
有時需要在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>
當然,還有許多其它的方法做到上述相同效果。但上述方法直接簡明,容易理解和使用。