有时需要在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>
当然,还有许多其它的方法做到上述相同效果。但上述方法直接简明,容易理解和使用。