asp.net c# MVC: How do I live without ViewState?

C#asp.net MvcViewstate

C# Problem Overview


I am just looking into converting WebForms to MVC:

In .net MVC, what concepts make ViewState something thats not required?

If a form is posted back on iteself etc (ie a postback)? how does the page/usercontrol maintain its state?

What tricks are people doing to maintain some kind of state and not resort to session state?

Surely, a completely stateless environment cant exist?

C# Solutions


Solution 1 - C#

But of course it can. In fact, the web is stateless. Any thoughts to the contrary are the aberration, in fact.

Web Controls are gone in MVC. There are no events firing on the server side. This is replaced by two different mechanisms--URLs and POSTing form data. Proper use of these will replace your need for the ViewState.

In a conventional ASP.NET web application, you would place a LinkButton on your webpage that would perform function X. ASP.NET would stick lots of ViewState cruft, javascript and other stuff into the webpage so that, when the user clicks on the button and "posts back" to the website (by submitting a form nobody knows existed), ASP.NET reconstructs what happened and determines a particular button event handler must be executed.

In MVC, you construct your link to access a particular route. The route describes what the user wishes to do--/Users/Delinquent/Index (show a list of all delinquent users). The routing system in MVC determines which Controller will handle this route and which method on that controller will execute. Any additional information can be transmitted to the controller method by URL query string values (?Page=5 for the 5th page of delinquents).

In addition to URLs, you can use HTML forms to POST back more complex information (such as a form's worth of data) or things that won't fit in a query string, such as a file.

So you "maintain" state via query strings and form POST values. You'll find that, in fact, there isn't that much state to maintain in the end. In fact, having to maintain lots of state is a good indication that your design is lacking or that you're trying to do something that doesn't fit a website model.

Solution 2 - C#

Some related questions:


In most traditional web languages the concept of a stateful environment is actually quite uncommon. ASP.NET Webforms is an exception to the rule and it creates that exception by reinventing a lot of standards. The goal behind Webforms is essentially to abstract the concept of HTML and web development in general so that the line between desktop application and web application blurs from a development standpoint. What this generally tends to mean is that the solution that ASP.NET Webforms provides, although effective, is a jack-of-all-trades implementation which results in some very verbose output that works well enough to satisfy most. Conversely, the core advantage of ASP.NET MVC is that it gives HTML output control back to the developer and allows them to create strongly-architected, RESTful web applications that are better defined and cleaner in their implementation and presentation- despite sacrificing some level of convenience.

Arguably, one of the largest drawbacks of the Webforms model is the ViewState because it clutters the output, increases the page size dramatically in certain scenarios, and is often the equivalent of using a jackhammer to hang a picture. Rather than trying to make use of ViewState in your MVC application (or anything resembling it), you should begin to use patterns which explicitly control the fields in your forms and optimize your input and output operations with only the most relevant data. In addition to the changes in markup, you will also learn to build better designed solutions that can be exposed within your application and externally.

The number one comparison I like to make is simply: Webforms builds Web Pages, but MVC builds Web Applications. If your day-to-day work is primarily building pieces of a website, or adding small chunks of functionality, you will often find Webforms to be much easier and less time consuming; on the other hand, if you want to build a complete application that is testable, scalable, and flexible, MVC is your calling.

Solution 3 - C#

viewstate is just a big, ugly hidden form field.

Write out your own hidden form fields, and encrypt them if you have to.

Fortunately, there's no longer any simple way to dump lots and lots of data into the page, so you have to be judicious about what you want to save.

Solution 4 - C#

> If a form is posted back on itself etc > (ie a postback)? how does the > page/usercontrol maintain its state? What tricks are people doing to maintain some kind of state and not resort to session state?

The posted ViewData (or strongly-typed object bound to the page) can be pushed out to the view again. See "Integrating Validation and Business Rule Logic with Model Classes" in this page. It shows how you can post a form, validate it, and return the fields back to the form if an error occurs.

> In .net MVC, what concepts make > ViewState something thats not > required?

Representational State Transfer (REST).

Solution 5 - C#

MVC has some advantages over WebForms but it also has some disadvantages as well as I covered detail in this answer. I think the fundamental question that you have to ask yourself is whether ViewState is a problem for you now - and is it such a problem that you must rewrite your application? If not, then Learning MVC is a worthy goal (it really is quite cool) but not one that I'd risk business for.

With that being said, ViewState can actually be disabled in a surprisingly large number of cases. It is used primarily to persist the value of controls through a post-back. So, for example, if you have a text box whose value you must check on the server side as well as a bunch of other fields, ViewState will let you handle the post-back, catch the error (and show a label) and then return the user to the form with all of their entries intact. However, if a form is only going to be filled out and posted back and you'll then be redirecting to another page, you can safely disable it.

Finally, you ask what people are doing to avoid Session state. Is there a reason to avoid session state? Surely you don't want much information there but avoiding it altogether is really not necessary and, in fact, will cost you one of the most powerful tools in your arsenal.

Solution 6 - C#

All of the answers saying that ASP.NET MVC does not use state are pretty much correct. But ASP.NET MVC does in fact use some state, although it does not work anything like ViewState.

Usually, when someone POSTs data to your application, you will want to validate the data and display an error if the data are not valid. However, if you just return the page containing the error message immediately, when the user hits F5 to reload the page, the data will be resubmitted. This is usually not what you want. Thus, when you realize that the data POSTed are not valid, you want to tell the users to GET the page (or perhaps another page) and show an error message. You do that by returning an HTTP Redirect status code. However, once the user's GET request comes in, how do you know what error message to display? You will have to somehow remember this from the time you (the server) are handling the POST until you are handling the GET.

To do this you use an ASP.NET MVC feature called TempData. This is actually just a wrapper around Session which ensures that whatever you shove into the TempData dictionary will stay there until the next request and no longer.

Solution 7 - C#

Consider the fact that the REST movement in web programming is predicated on the idea that state is bad for a program. The Wikipedia has a decent description with references: http://en.wikipedia.org/wiki/Representational_State_Transfer

Coming from tranditional ASP.NET and the rich event model it provides, MVC can be quite jarring. It does require managing some things that were invisible to you before, but I think that the value in terms of testability (REST pages can be triggered easily without creating a complex viewstate and by definition the server isn't holding state so I can test a page/feature in isolation) offsets the learning curve.

For some discussion of MVC in ASP.NET and REST: http://blog.wekeroad.com/2007/12/06/aspnet-mvc-using-restful-architecture/

Solution 8 - C#

The state is the model which is in the database. You can carefully cache the database to reduce page load times.

Solution 9 - C#

Auto generated view state does not exist in MVC, but you can write your own simply using hidden fields,

In MVC you will not see a lot of encrypted chars at the top of the page which you don't need most of them.

Solution 10 - C#

Actually it does. You have to forget about the way persistance was made up with the viewstate.

You have also to convert in your mind postback onto a page to "call to a controller". This way things will be easier to understand afterwards. Instead of calling a page , you're calling a controller which returns a view. So either your are building your whole "page" again and again on every call, or you decide to deal only with what is really impacted by the action. If the button is changing a div, why reload the entire page. Just make you call to your controller and return what should be the new data in your div.

for example let's imagine a master/detail scenario:

<h2>Groups</h2>
    <div id="GroupList">
    </div>
    <div id="GroupDetail" title="Detail Group">
</div>

The list of group is loaded once in the div and there is an ajax call possible to a controller for each item of the list of group :

<%= Ajax.ActionLink("Edit", "DetailLocalisationGroup", 
                     new { id = group.Id }, 
                     new AjaxOptions() { 
                         UpdateTargetId = "DetailLocalisationGroup", 
                         OnSuccess = "InitialisationDetailGroup" })%>

which calls this action DetailLocalisationGroup which is to feed the div GroupDetail with html.

[AcceptVerbs("POST")]
public ActionResult DetailLocalisationGroup(int id)
{
    LocalisationGroup group = servicelocalisation.GetLocalisationGroup(id);
    return View("DetailGroup", group);
}

There is now a form in the div, and when pushing the submit button of this form, we just send the information we really need to a controller which would then save the data in the database.

During all these events, the GroupList was filled with stuff that was displayed on the client screen, but no interaction was needed there and so why bother oneself with a viewstate for these...

Solution 11 - C#

You can imitate view state with MVC3Futures project. It will save the whole model in view.

All you have to do is to serialize model and encrypt it in view.

@Html.Serialize("Transfer", Model, SerializationMode.EncryptedAndSigned)

And in controller add deserialized attribute.

public ActionResult Transfer(string id,[Deserialize(SerializationMode.EncryptedAndSigned)]Transfer transfer)

Solution 12 - C#

After reading all these posts, it sounds like MVC is not good for LOB kind of applications, where you will have lot of controls and, CRUD operations and you want to maintain the state of the controls. There are plenty of reasons where you want the user to stay on the same view & maintain state after submit operations is done. For example to show errors, server side validation messages, success messages, or to perform any other action. redirecting user to some other view to show these messages is not practical.

Solution 13 - C#

You can store any object in the session state.

 HttpContext.Session["userType"] = CurrentUser.GetUserType();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark RedmanView Question on Stackoverflow
Solution 1 - C#user1228View Answer on Stackoverflow
Solution 2 - C#Nathan TaylorView Answer on Stackoverflow
Solution 3 - C#Rob Fonseca-EnsorView Answer on Stackoverflow
Solution 4 - C#Robert HarveyView Answer on Stackoverflow
Solution 5 - C#Mark BrittinghamView Answer on Stackoverflow
Solution 6 - C#RuneView Answer on Stackoverflow
Solution 7 - C#GodekeView Answer on Stackoverflow
Solution 8 - C#Tamas CzinegeView Answer on Stackoverflow
Solution 9 - C#Amr ElgarhyView Answer on Stackoverflow
Solution 10 - C#ArthisView Answer on Stackoverflow
Solution 11 - C#jan salawaView Answer on Stackoverflow
Solution 12 - C#LP13View Answer on Stackoverflow
Solution 13 - C#fireydudeView Answer on Stackoverflow