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

        如下是视图Index.cshtml的代码

 

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

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

 

posted on 2018-03-19 10:27  freeliver54  阅读(722)  评论(0编辑  收藏  举报

导航