[转]ASP.NET MVC4中@model使用多个类型实例的方法

本文转自:http://blog.csdn.net/hulihui/article/details/48199897

有时需要在ASP.NET MVC4的视图的@model中使用多个类型的实例,.NET Framework 4.0版本引入的System.Tuple类可以轻松满足这个需求。

假设Person和Product是两个类型,如下是控制器代码。

[csharp]view plaincopy

  1. using System;
  2. using System.Web.Mvc;
  3. namespace Razor.Controllers
  4. {
  5. public class HomeController : Controller
  6. {
  7. Razor.Models.Product myProduct = new Models.Product { ProductID = 1, Name = "Book"};
  8. Razor.Models.Person myPerson = new Models.Person { PersonID = "1", Name = "Jack" };
  9. public ActionResult Index()
  10. {
  11. return View(Tuple.Create(myProduct,myPerson)); // 返回一个Tuple对象,Item1代表Product、Item2代表Person
  12. }
  13. }
  14. }

如下是视图Index.cshtml的代码

[html]view plaincopy

  1. @model Tuple<Razor.Models.Product, Razor.Models.Person>
  2. @{
  3. Layout = null;
  4. }
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <meta name="viewport" content="width=device-width" />
  9. <title>Index</title>
  10. </head>
  11. <body>
  12. <div>
  13. @Model.Item1.Name
  14. </div>
  15. </body>
  16. </html>

当然,还有许多其它的方法做到上述相同效果。但上述方法直接简明,容易理解和使用。