1、cookie
继续讲解MVC的内置对象cookie
相对不安全
1)保存cookie
public ActionResult Index() { // 设置cookie以及过期时间 Response.Cookies.Add(new HttpCookie(name: "userId") { Value = "128idn62dx", Expires = DateTime.Now.AddDays(3) }); return Content("ok!"); }
2) 获取cookie
public ActionResult Index() { return Content(Request.Cookies["userId"].Value); }
3)移除cookie
1 public ActionResult Index() 2 { 3 // 设置cookie以及过期时间 4 Response.Cookies.Add(new HttpCookie(name: "userId") 5 { 6 Expires = DateTime.Now.AddDays(-1) 7 }); 8 return Content("ok!"); 9 }
2、Application
1) 是全局的
设置application
1 public ActionResult Index() 2 { 3 HttpContext.Application["user"] = "Linda"; 4 return Content(HttpContext.Application["user"].ToString()); 5 }
3、Server
包含了服务器的常用方法
public ActionResult Index() { Server.Transfer(path: "html页地址"); return Content("ok"); }
路径不变,内容改变
.MapPath 虚拟路径转物理路径
2、控制器(controller)与视图(view)的数据通信
Controller里面每个方法都可供访问
1) Controller => view
①ViewBag
控制器文件
1 public ActionResult Index() 2 { 3 ViewBag.Info = "info from Controller"; 4 return View(); 5 }
视图文件
1 @{ 2 ViewBag.Title = "Index"; 3 } 4 5 <h2>App Page for DemoController</h2> 6 <!--访问Controller内数据--> 7 8 <p>@ViewBag.Info</p>
②ViewData
public ActionResult Index() { ViewData["Name"] = "fiona"; return View(); }
@{ ViewBag.Title = "Index"; } <h2>App Page for DemoController</h2> <!--访问Controller内数据--> <p>@ViewData["Name"]</p>
③TempData
可跨页面传递数据,仅能被访问一次,之后会被清除
public ActionResult Index() { TempData["token"] = "23vf5c"; return View(); }
@{ ViewBag.Title = "Index"; } <h2>App Page for DemoController</h2> <!--访问Controller内数据--> <p>@TempData["token"]</p>
上面3中方法传递的都是不主要的数据
主要的数据通过下面的方法传递
④通过View方法传递
1 @{ 2 ViewBag.Title = "Index"; 3 } 4 5 <h2>App Page for DemoController</h2> 6 <!--访问Controller内数据--> 7 8 <p>@Model.Name</p> 9 <p>@Model.Sex</p>
1 public ActionResult Index() 2 { 3 return View(new Animal() 4 { 5 Name = "cat", 6 Sex = "male" 7 }); 8 }
ide不能进行识别来提示,可声明
@{ ViewBag.Title = "Index"; } @model MVCStudy.Models.Animal <h2>App Page for DemoController</h2> <!--访问Controller内数据--> <p>@Model.Name</p> <p>@Model.Sex</p>
Model内的类型要与View方法参数内的一致
其它方式:指定视图页并传参
public ActionResult Index() { return View("ShowData",new Animal() { Name = "cat", Sex = "male" }); }
@{ Page.Title = "此处显示标题"; //Layout = "此处显示你的布局页"; } @model MVCStudy.Models.Animal <div> this iss ShowData page </div> <div> data from democontroller</div> <p>@Model.Name</p> <p>@Model.Sex</p>
同时指定布局模板,下面的mylayout位于shared目录下
public ActionResult Index() {
// 视图名,模板页,数据 return View("ShowData",masterName:"_MyLayout",new Animal() { Name = "cat", Sex = "male" }); }
------------恢复内容结束------------