I have used ASP.Net Webforms. I am currently learning MVC, and I have read that ASP.NET MVC–generated pages don’t contain any View State data. Can someone explain what is the substitute for viewstate in MVC? How come they eliminated viewstate? As controls also have viewstate, what's the alternative in that case?
1 Answers
In webforms, the first page load is distinguished by using IsPostback property and server controls are basically initialized with data or initial values in Page_Load event. These initial settings are persisted on subsequent post back events for the page. As you may already know, all this is accomplished by viewstate which is basically a hidden variable that contains state of all server controls on the page and gets posted back for each postback event.
MVC doesn't have this mechanism and is completely stateless i.e, we need to manually assign values of controls for each request. For ex:
In Web forms
ASPX page:
<asp:TextBox id="txtName" runat="server"/>
<asp:Button id="btnSubmit" Text="submit" onclick = "btnSubmit_click" />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
txtName.Text = "test1";
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
//some code
}
Enter a value and click on submit button, the value gets persisted event after postback due to viewstate.
In MVC
View
@using(Html.BeginForm()){
<input id="Name" type="text" name="Name"/>
<input type="submit" value="submit" />
}
Controller
[HttpPost]
public ActionResult Index(FormCollection values)
{
return View();
}
Enter a value and click on submit button, the value is not persisted across postback since there is no such persistence mechanism. So we need to achieve it manually
View
@using(Html.BeginForm()){
<input id="Name" type="text" name="Name" value="@ViewBag.Name"/>
<input type="submit" value="submit" />
}
Controller
[HttpPost]
public ActionResult Index(FormCollection values)
{
ViewBag.Name = values["name"];
return View();
}
Note: I have used ViewBag only to show an example, ideally we need to pass viewmodel from controller.
Additional Inputs
Apart from its role of persisting state, ViewState can also be used to store values, say for ex: ViewState["test"] = objectoranyothervalue. In MVC, there are other techniques for state management like ViewBag, ViewData and TempData but difference is they don't get posted back to server like ViewState. They are used to just pass data from controller to view.