【ASP.NET】@Model类型的使用详解
有时需要在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>
当然,还有许多其它的方法做到上述相同效果。但上述方法直接简明,容易理解和使用。
有时候我们在页面中会看见@model的语句,都是用于从后台向前端页面传递数据的,下面我们来看看一个案例:
(1)定义Model实体
- public class SearchWithFundingList
- {
- /// <summary>
- /// 方案分类
- /// </summary>
- public int ProjectCategory { get; set; }
- /// <summary>
- /// 发起时间小
- /// </summary>
- public string MinAddDate { get; set; }
- /// <summary>
- /// 发起时间大
- /// </summary>
- public string MaxAddDate { get; set; }
- /// <summary>
- /// 状态
- /// </summary>
- public int State { get; set; }
- /// <summary>
- /// 昵称
- /// </summary>
- public string NickName { get; set; }
- /// <summary>
- /// 用户id
- /// </summary>
- public int Mid { get; set; }
- }
(2)传递Model
- private SearchWithFundingList GetFormWithFundingNow(int id, int uid)
- {
- SearchWithFundingList model = new SearchWithFundingList();
- model.Mid = uid;
- model.State = WithFundingStateKey.Doing;
- model.ProjectCategory = id;
- return model;
- }
注意:一定要在最后return 实体,不然前台的Model实体是null
(3)具体调用
在页面代码最上面添加上实体的声明
- @{Layout = null;}
- @model StockFunds.Entities.DTO.SearchWithFundingList
接下来就可以在页面里使用Model(这里的实体就是指SearchWithFundingList实体),并且此时的Model已经是强类型了,我们可以点出具体的属性,非常方便
- <span class="state">Model.State</span>元</span>
接下来是一个模拟用户登录的表单:
HomeController.cs
namespace Test.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; return View("~/Views/Home/Login.cshtml"); } public String Login(User user) { String name = user.Name; String password = user.Password; if ("张飞".Equals(name) && "abc".Equals(password)) { return "登录成功"; } else { return "登录失败"; } } } }
Login.cshtml
@{ Layout = null; } @model Test.Models.User <html> <head> <title>用户登录</title> </head> <body> <div> <form action="Home/Login" method="post"> 用户名:@Html.TextBoxFor(model=>model.Name)<br/> 密码:@Html.TextBoxFor(model=>model.Password)<br /> <input type="submit" value="提交" /> </form> </div> </body> </html>