This article illustrates several forms of the MVC data transfer in asp.net. Share to everyone for your reference. Specifically as follows:
In asp.net MVC development, controller needs to provide model to view, and then view renders this model HTML. This article describes three ways to transfer data from controller to view to achieve a DropDownList display.
The first type: ViewData
ViewData is a dictionary. Use it very simply, look at the following code:
Public ActionResult viewdataway (int id)
{book Book
=bookrepository.getbook (ID);
viewdata["Countries"] = new SelectList (phonevalidator.countries, book. Country);
Return View (book);
}
In view, use the following code to take the value:
<div class= "Editor-field" >
<%= html.dropdownlist ("Country", viewdata["Countries"] as SelectList)%>
<%: html.validationmessagefor (model => model. Country)%>
</div>
The code above uses as to convert it to selectlist.
The post code is processed as follows:
[HttpPost]
Public ActionResult viewdataway (int ID, formcollection collection)
{book Book
= Bookrepository.getbook (ID);
Updatemodel<book> (book);
Bookrepository.save (book);
Return redirecttoaction ("Details", new {id=id});
}
The second type: ViewModel
Using the ViewModel method, we first create a Bookviewmodel, the code is as follows:
public class Bookviewmodel {public book book
{get
;
Set;
}
Public SelectList Countries
{get
;
Set;
}
Public Bookviewmodel (book book)
{book
= Book;
Countries = new SelectList (Phonevalidator.countries,book. Country);
}
The code that uses ViewModel to store data in the controller's Aciton is as follows:
Public ActionResult viewmodelway (int id)
{book Book
= Bookrepository.getbook (ID);
Return View (new Bookviewmodel);
}
In view, this approach is better than the first: it supports intelligent sensing.
The effect is the same as the first method.
The third type: TempData
Using TempData is the same as using the ViewData method.
The action code is as follows:
Public ActionResult tempdataway (int id)
{book Book
= Bookrepository.getbook (ID);
tempdata["Countries"] = new SelectList (phonevalidator.countries, book. Country);
Return View (book);
}
The code for the view value is as follows:
<div class= "Editor-field" >
<%= html.dropdownlist ("Country", tempdata["Countries"] as SelectList)%>
<%: html.validationmessagefor (model => model. Country)%>
</div>
Effect: The first approach is the same.
The difference between TempData and ViewData
Take a simple test and look at the difference between TempData and ViewData.
Public ActionResult Test1 ()
{
tempdata["text"] = "1-2-3";
viewdata["text"] = "1-2-3";
Return redirecttoaction ("Test2");
Public ActionResult Test2 ()
{
string text1 = tempdata["text"] as String;
String text2 = viewdata["text" As String;
return View ();
}
Redirecttoaction jump Action, the ViewData value has been emptied, and tempdata has not been emptied, which is one of their differences.
I hope this article will help you with the ASP.net program design.