4.1 View详解
View和Action之间前后台数据传递的方式有如下几种:
- 弱类型 ViewData[""]
- 动态型 ViewBag//dynamic
- 动态类型 Model
- 临时存储TempData[""]
- 后台:return View(data);//存入ViewData.Model
- 前台:Medel//其实就是WebViewPage.Model
4.1.1 实例
添加Home控制器,Models目录中添加User模型类:
Models-->User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcViewApp.Models
{
public class User
{
public string Name { get; set; }
}
}
HomeControler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcViewApp.Models;
namespace MvcViewApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ViewData["One"] = "天机老人";
ViewBag.Two = "郭靖";
var _user = new User { Name = "小龙女" };
TempData["Four"] = "欧阳克";
return View(_user);//等于ViewData.Model = _user
}
}
}
添加视图:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>1: @ViewData["One"]</p>
<p>2. @ViewBag.Two</p>
<p>3. @Model.Name</p>
<p>4. @TempData["Four"]</p>
运行结果
网友评论