有时需要在ASP.NET MVC4的视图的@model中使用多个类型的实例,.NET Framework 4.0版本引入的System.Tuple类可以轻松满足这个需求。
public ActionResult Text2() { Person person = new Person() { PersonId = 1, Name = "Tom" }; Product product = new Product() { ProductId = 2, Name = "Jim" }; Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(5,"AAA"); return View(Tuple.Create(person, product,dic)); }
如下是视图Index.cshtml的代码:
@model Tuple<Demo1.Controllers.Person, Demo1.Controllers.Product, System.Collections.Generic.Dictionary<int,string>> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Text2</title> </head> <body> <div> @Model.Item1.Name <br /> @Model.Item2.Name <br /> @foreach (var item in Model.Item3.Values) { <h5>@item</h5> } </div> </body> </html>