views:

771

answers:

10

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?

+1  A: 

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

DrJokepu
+4  A: 

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.

Rob Fonseca-Ensor
encrypted? It's not encrypted by default. You mean encoded. You can easily decode a viewstate.
Steven
@steven you're right, it's not always encrypted: http://msdn.microsoft.com/en-us/library/aa479501.aspx
Rob Fonseca-Ensor
+34  A: 

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.

Will
Quite agree - it's just not necessary, and, in fact, much easier without it.
Paddy
The less state your website has the easier it is to code and test and maintain. The problem is that state is such a huge crutch it can be hard to get rid of it at first.
Will
+1 for stateless view layer as good design. Stateless views are vastly misunderstood.
Michael Meadows
Been looking at MCV for about a month now and its all making sense. It does mean re-implementing a few things, but in the long run the efficiency saved is immense. Thanks for the answers..
Mark Redman
+1  A: 

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.

Amr ElGarhy
+3  A: 

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).

Robert Harvey
+6  A: 

Some related questions:

http://stackoverflow.com/questions/1285547/maintaining-viewstate-in-asp-net-mvc http://stackoverflow.com/questions/366151/asp-net-mvc-doesnt-work-with-viewstate-and-postback


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 that 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- at the cost of convenience.

One of the largest drawbacks of the Webforms model is ViewState because it clutters the output, increases the page size dramatically in certain scenarios, and is the equivalent of using a jackhammer to hang a picture most of the time. Rather than trying to make use of ViewState in your MVC application (or anything resembling it), you will begin to depend on things like controlling the fields in your forms to ensure all of the data you need is available on a given request, and optimizing 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.

Nathan Taylor
+1  A: 

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...

Yoann
Hi, ok I am going through some tutorials and think I grasp what you're saying... however dont get how for instance you can list things without having a Template layout design on the UI, do you have to hard-code some kind of Html Template in the Controller? That doesnt seem like a separation of concern there?
Mark Redman
..or am I missing something...
Mark Redman
Hope it is not too late... Well, you don't need Html template in the controller. The only thing you need is to say which view to use, and to give to this view the object, it needs. It works the same way as a User Control.
Yoann
+1  A: 

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.

Mark Brittingham
+1  A: 

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/

Godeke
+1  A: 

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.

Rune