ASP. net mvc has something called TempData. Its type is TempDataDictionary, which is different from ViewData and ViewBag in that
It uses sessions internally to store information, which can be understood as temporary storage. Although the session is used to save information, its lifecycle is "a webpage request ".
With this, we can use it to transfer values between actions in MVC. The following are some of my experience in transferring values. Please ignore them.
Suppose we have a student management page, which includes the student adding function and the student display list. We use an Action to display all the information, just like a web form.
Then there is such an action in the controller.
? [HttpGet]
Public ActionResult Students ()
{
ViewBag. title = "Add Student Page ";
ViewBag. jsMessage = TempData ["jsMessage"] = null? "": TempData ["jsMessage"]. ToString (); // judge and assign a value to ViewBag
Return View (StudentsPage_Load ());
}
To Add students, we must have an Add action as follows:
? [HttpPost]
Public ActionResult Add (Students student)
{
If (ModelState. IsValid)
{
StudentsBLL bll = new StudentsBLL ();
Bll. Add (student );
TempData ["jsMessage"] = "alert ('success ');"; // use TempData to store data
}
Return RedirectToAction ("Students ");
}
Pay attention to the comments in the above Code. It means that after successful addition, the original page is returned. That is to say, this Add action does not have a corresponding view.
After successfully adding students, you must use JS to pop up a successfully added dialog box on the original page. This can be written in the View of Students.
? <Script type = "text/javascript">
@ Html. Raw (@ ViewBag. jsMessage)
</Script>
@ Html. Raw indicates that the output is not escaped. Note the following. If you write data directly in the cshtml File
? TempData ["jsMessage"] outputs the escape characters. But if it is written like this:
? @ Html. Raw (TempData ["jsMessage"])
? An error will be reported during page compilation. Therefore, you must add it to the Students Action.
? ViewBag. jsMessage is used as the data owner.