.net-mvc前后端4种传值方式
2020-12-01 本文已影响0人
浅谈码生活
1.)ViewData:后端以字典形式赋值(base.ViewData["key"]=value),前端显示界面直接(@ViewData["key"])调用。
2.)ViewBag:ViewBag为dynamic类型,后端可以直接进行赋值(base.ViewBag.name=""),前端显示界面直接(@ViewBag.name)调用。注:ViewBag可能会覆盖ViewData的数据
3.)TempData:后端以字典形式赋值(base.ViewData["key"]=value),前端显示界面直接(@TempData["key"])调用,但TempData的数据会保存到浏览器的session中,所以可以跨试图调用。
4.)Model:后端为正常实体类,在前端显示界面使用时,开头先引用命名空间,并以(@model ClassName)标记,后面直接(@Model.Name)使用。
后端控制器赋值
public ActionResult Index()
{
base.ViewData["ViewDataCurrentUser"] = _UserList[0];
base.ViewData["testProp"] = "jeff";
base.ViewBag.testProp = "判断ViewBag.testProp 有没有覆盖ViewData[testProp]"; //会和ViewData["testProp"] 冲突,以后者为准;
base.ViewBag.Name = "name";
base.ViewBag.ViewBagCurrentUser = this._UserList[1];
base.TempData["TempDataCurrentUser"] = this._UserList[2];
base.TempData["testProp"] = "fresh"; //TempaData 存储在Sesssion中; 可以跨Action传递值
CurrentUser currentUser = this._UserList[3];
return View(currentUser);
}
前端视图使用
@model CurrentUser
@{
ViewBag.Title = "FirstIndex";
CurrentUser ViewDataCurrentUser = ((CurrentUser)ViewData["ViewDataCurrentUser"]);
CurrentUser TempDataCurrentUser = ((CurrentUser)TempData["TempDataCurrentUser"]);
}
<h2>FirstIndex</h2>
<h3>ViewData["ViewDataCurrentUser"].Name:@(((CurrentUser)ViewData["ViewDataCurrentUser"]).Name)</h3>
<h3>ViewData["ViewDataCurrentUser"].Name:@(ViewDataCurrentUser.Name)</h3>
<h3>ViewData["testProp"]:@ViewData["testProp"]</h3>
<h3>ViewBag.Name:@ViewBag.Name</h3>
<h3>ViewBag.ViewBagCurrentUser.Name:@ViewBag.ViewBagCurrentUser.Name</h3>
<h3>TempData["TempDataCurrentUser"].Name:@(((CurrentUser)TempData["TempDataCurrentUser"]).Name)</h3>
<h3>TempData["TempDataCurrentUser"].Name:@(TempDataCurrentUser.Name)</h3>
<h3>TempData["testProp"]:@TempData["testProp"]</h3>
<h3> ViewBag.testProp:@ViewBag.testProp</h3>
<h3>Model.Name:@Model.Name</h3>