ViewData and TempData properties to pass objects to the view page
As already mentioned, using ViewData can pass data from controller to view
In the previous article we established the Eicecontroller class
In the example in this article, we'll change this controller
public class EiceController : Controller
{
public ActionResult Index()
{
ViewData ["ViewData"] = "在这里显示ViewData";
TempData ["TempData"] = "在这里显示TempData";
return View();
}
public ActionResult Index2()
{
return View ("Index");
//这里指定了规定显示的View文件即Eice目录下的Index.aspx
}
}
We removed the index parameters and provided viewdata and tempdata assignments.
In the views/eice/index.aspx view, we write the following code
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
1:<%=ViewData["ViewData"]%><br />
2:<%=TempData ["TempData"]%>
</asp:Content>
Note that the top 1.2 is not the line number, I wrote it.
Next we run the project
Visit http://localhost/Eice/Index
You can see that running gets the following
1.在这里显示ViewData
2.在这里显示 TempData
Visit Http://localhost/Eice/Index2 again
Display results as
1.
2.在这里显示TempData
Here 1 shows the contents of the ViewData, 2 is the content passed by TempData
We can see that ViewData only works in the current action.
But TempData can be similar to the session to other pages still exist, but only one page of access (similar to the Flash in monorail)
TempData is typically used to temporarily cache content or to pass error messages when an error page is thrown.