需求:同时查看一个产品信息和发布会员的信息
- 方案1:新建ViewModel
- 方案2:ViewData、ViewBag
- 方案3:Tuple<obj1,obj2>
在这里我们使用方案3来实现这个问题,方案1和方案3大家都懂
controller代码
using System;
using System.Web.Mvc; namespace Razor.Controllers
{
public class HomeController : Controller
{
Razor.Models.Product myProduct = new Models.Product { ProductID = , Name = "Book"};
Razor.Models.Person myPerson = new Models.Person { PersonID = "", Name = "jim" }; public ActionResult Index()
{
return View(Tuple.Create(myProduct,myPerson)); // 返回一个Tuple对象,Item1代表Product、Item2代表Person
} }
}
view代码
@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 //book
@Model.Item2.Name //jim
</div> </body> </html>
//Tuple.Create(...)最多可添加8个对象