No viewstate or postback in ASP MVC? - asp.net

I've been learning about MVC for a while, and I think I pretty much understand what it's all about. But there is one thing I don't yet understand: I keep hearing with MVC that there is no viewstate nor postback.
Can someone explain what this means in simple terms?

Try this SO answer which addresses the same question.
Extra info after comment/question:
ASP.Net web forms can use viewstate to store the state of server controls on the page and to manage invocation of server side events such as a button click. The idea is to present a programming model that is similar to the Win Forms approach to make it easier for Win Forms developers to transition and knock out browser based apps. To learn about it in depth you should hit google and learn about the asp.net page life cycle which will explain the overall process and explains where viewstate processing fits in. Here's a pretty good explanation.
ASP.Net MVC is a different programming model that uses different view engines to generate your markup - i.e. the content that actually streams back to your browser client. To an extent it removes a lot of the "magic" that web forms introduced but in return you can produce more standard markup and have greater control over what will be rendered to the client. If you're learning MVC take a look at the NerdDinner sample chapter which is a good tutorial as well as the MVC Music Store. Throughout those are good intros to doing MVC.
MVC doesn't use/need viewstate or postbacks as it's a different programming model. Which is better/more appropriate for any given project is a big debate that I'll let others have as I think both have their strengths and can be useful in different scenarios (although I personally mainly use MVC now...). You're right that things are done differently... you can't just work with the simple event driven approach that web forms imitates but then MVC has lots of strengths of its own which you'll find across countless blog posts comparing webforms vs MVC.

MVC Do not have viewstate and session but you can use TempData Object instead of viewstate.
in your controller you can bind like this TempDate["MyKey"]="My Value" and in the next request you can get your value in action like String s=TempData["MyKey"]

Related

How does ObjectDataSource relate to traditional MVC pattern?

(Apologies for the vagueness of this question. It is the result of some muddy thinking on my part.)
I am designing a small website with an MSSQL DB. I have just stumbled across the ObjectDataSource class. I think I understand it, but I don't see how it relates to the traditional MVC design pattern, if at all.
The class, according to Microsoft, is designed to sit between the UI (View) and the database, and as such, I would think of it as a Controller. It does indeed map UI actions to behaviours, but it also contains code for writing to the database, which is not something I would expect a Controller to do (but I may be wrong).
It seems to me that it is both the Controller and the Model, but I get the feeling I am not seeing something here.
That's a lot of words to say I am very confused. I would be very grateful to anyone who can point me at anything that might help me to understand what I am missing here.
The purpose of the ObjectDataSource is to intermediate between the view and some code that retrieves your data, not to the database directly. It is not a controller, but something that would call your code to get the data. A better description would be from an MVP scenario, where in MVP the view can manage itself, and the ObjectDataSource is a control that makes that management easier. However, the ObjectDataSource may make it harder to work with a traditional MVP or MVC design implementation out of the box, depending on the framework setup.
I personally don't like this control; I never use it as I'd rather code it so it's easier to see how the binding takes place, in addition to when the binding takes place. My personal opinion.
ObjectDataSource is not used in asp.net MVC if that's what you mean "traditional MVC design pattern". It's used primarily in WebForms development.
It's usually dropped onto a webform component and configured via the UI, although it doesn't have to be. It provides an abstraction that allows other WebForms controls to interact with an object model in a manner that is similar to the way in which these controls work with Databases. This object model may ultimately come from a database, but it allows you to insert your own database methodology in between.
WebForms does not lend itself to the traditional MVC pattern due to some technical issues which complicate using it in that way. A cleaner pattern for use with WebForms is the MVP (Model View Presenter) pattern.

So does it mean RAZOR without MVC cannot even do the event handler stuff?

I am new to RAZOR and now I need to trigger an event when users clicked a button, so I can run a lines of code to handle the event.
I don't want to use it with MVC, and I don't want to use JavaScript because I only want to explore the power of RAZOR.
I was surprised when someone told me that the way of event-drive methods has been discarded in the RAZOR, that's alright. But my question is
what is the way to handle/response a click event (in the RAZOR syntax) which is the simplest thing in the ASP.NET Web Form applications?
The reason why I'm asking this question is I found that even the easiest thing like I want to write a fragment of code to response users' input hard to be done(or should I say there is no way to do it) in the RAZOR.
You can take a look the discussion in my previous post.
ASP.NET RAZOR cannot capture the event
I hope there are some guys who can guide me through the first and tough step.
Thanks.
Update:
It seems that there is really no way to handle the user events in any way without the help of MVC framework. Thank you guys for your answers. I'd like to leave this post a few days longer and hopefully I could see someone post something interesting.
Thank you again.
There is no such thing like a click event in Razor.
Event handling is a concept that was used in WinForms. The event model in classic ASP.NET WebForms was an effort to translate the Windows programming model to the web, which, frankly, didn't work very well. A stateful event model and web programming pretty much contradict each other.
If you want to work with events then use classic ASP.NET WebForms. If you want to embrace the web and not work against it, learn ASP.NET MVC, Razor, etc.
Don't try to fit a stateful legacy paradigm on a stateless infrastructure. This is what Microsoft did with WebForms and that is where it should stay.
Razor is only for use with ASP.NET MVC. You can't use it with the WebForms model, though there are some advanced and messy scenarios where some folks mix the two. This isn't what you want.

ASP .NET confusion - server controls

I have read through the information in this question: Controls versus standard HTML but am still rather confused.
The situation was I was asked to do a web project where I made a wizard. When I was done with the project everyone asked why I had used an <asp:Wizard...>. I thought this was what was being asked for, but apparently not, so after this I was led to believe that server controls were just prototyping tools.
However, the next project I did my DB queries through C# code-behind and loaded the results via html. I was then asked why I had not used a gridview and a dataset.
Does anyone have a list of pros and cons why they would choose to use specific html controls over specific server controls and why? I guess I'm looking for a list... what server controls are okay to use and why?
EDIT:
I guess this question is open ended, so I'll clarify a few more specific questions...
Is it okay to use very simple controls such as asp:Label or do these just end up wasting space? It seems like it would be difficult to access html in the code behind otherwise.
Are there a few controls that should just never be used?
Does anyone have a good resource that will show me pros and cons of each control?
Server Controls Rely on ViewState, Restrict Flexibility
Server controls were powerful tools to introduce WinForms developers to web development. The main benefit that Server Controls provide is a sense of statefullness and an event-driven development model. However, the state of web development has been maturing since the introduction of WebForms and server controls, which as a whole are being challenged with an increasingly critical view.
The main issue with Server Controls is that they try to abstract the behavior of the web too much, and in doing so, rely on ViewState data and server resources to perform their magic. ViewState data, when used excessively, can severely bloat the size of your page, resulting in performance problems.
Now it is possible to opt out of ViewState, but by then it probably is better to simply resort to regular HTML controls.
With HTML controls, you have precise control over the content of the web page and you have greater flexibility in what behaviors you want on your web page. Server controls offer limited client-side flexibility and force a lot of work to be performed on the server that can easily be performed in the browser with a good JavaScript framework.
Is it okay to use very simple controls such as asp:Label or do these
just end up wasting space? It seems
like it would be difficult to access
html in the code behind otherwise.
If you need to access the control in server side code, use a server control. If not, don't.
Are there a few controls that should just never be used?
Not in my (mid level) experience. The Wizard control, once you know how to use it, works as advertised (imagine coding all the features yourself, then do the math). I've used it and it resulted in a smooth and functional multi-page sign up form with intermediate saving of data.
Does anyone have a good resource that will show me pros and cons of
each control?
I do not, but I'd recommend using the right control for the right situation. Study the differences between a Repeater and a GridView, for example, and use the best choice for your needs.
There of course are alternatives. For one, MVC is gaining momentum. Personally I have not yet committed to learning it. As far as interactive forms and AJAX goes, many .NET devs opt to use JQuery for any validation and any AJAX (UpdatePanels being easy to use and horribly inefficient), with JSON as the transport mechanism to the server side.

Should I use Databinding to put data on my web page?

A video tutorial says I should use databinding to put data on my webpage. Is this the right thing to do?
It feels wrong to do it. Shouldn't there be a separation of concerns? The view should be separated from the code that connects to the database? In the aforementioned video, he connects to the database without going through a data access layer. What about the presenter/controller? It seems like we are completely bypassing those layers, going around the architecture.
It's important to realise that, when Microsoft produce a new UI technology, at least 2/3rds of it is designed to make it easy for newbies to slap together very simple 2-tier demo apps. I'm not saying this is a bad thing - after all, it helps us get up to speed on the technology quickly. However, when you are writing a proper n-tier app, then it's important to know which bits of the technology can and cannot be used.
For example, in ASP.NET WebForms, you should voluntarily restrict yourself as follows:
Don't use any data source control except for ObjectDataSource, and only use that for binding the Model to the View.
Don't use validation controls to validate input controls. Instead, pass all data to the Business Layer for validation and just display the resulting error messages on screen.
Don't use the built-in sorting/filtering/paging functions of the GridView. Instead, implement your own sorting/filtering/paging mechanism in the Business Layer.
To answer your original question: yes, data binding is very useful, as long as you bind to the Presentation Layer Model, rather than to a real data source.
Jonathan, you're thinking about ASP.NET MVC, whereas that tutorial is written for ASP.NET (which MVC developers like to refer to as ASP.NET Webforms). Have a look at the ASP.NET MVC tutorials here: http://www.asp.net/mvc/learn/
Keep in mind that although both have ASP.NET in the name, they're completely different programming philosophies. Webforms tries to mimic a stateful, event-driven form, like a Winform application. MVC, on the other hand, seperates it into models, views, and controllers, which fits very well with the web's stateless and request/response cycle.

Things I cannot do in ASP.NET MVC

Are there some things I cannot do with ASP.NET MVC?
Things that are only possible with ASP.NET WebForms,
or extremely much easier with WebForms?
We consider using ASP.NET MVC for a new project.
But I wonder if there are some obvious things we will not be able to do with ASP.NET MVC when compared to WebForms, or places where we will have to spend a lot of time with ASP.NET MVC.
The biggest one would be using existing 3rd party controls on your form. Most of the inbuilt controls are pretty easy to reproduce, but if you have a pet 3rd party control, you might have to host that on a regular (non-MVC) aspx page (luckliy this is supported).
Likewise, "web parts"
Also - the feature where ASP.NET uses different html for different clients (mobile, etc) becomes... different; you wouldn't want to do this by hand, but in reality most clients now work with standard html, so it is less of an issue in the first place.
Some things like i18n via resx files need extra work than is in the vanilla MVC template, but the samples are there on the internet.
One point... MVC is licensed only for MS/ASP.NET; so one thing you can't do (without violating the terms, as I understand it) is to run it in mono/Apache - but IANAL.
Now consider the things you can do with MVC, that you can't (or are hard) with vanilla:
routes instead of pages
automated input resolution (action arguments)
proper html control...
...enabling jQuery etc for simple AJAX
separation of concerns
testability
IoC/DI
multiple templating options (not just aspx/ascx)
re input resolution:
public ActionResult Show(string name, int? page, int? pageSize) {...}
will pick "name", "page" and "pageSize" off (any of) the route, query-string or form - so you don't have to spend lots of time picking out request values.
re templates - aspx/ascx aren't the only templating options. For example, see here; or you can write your own if you like... The view is not tied to ASP.NET controls at all.
Validation is not as easy as in WebForms. In Webforms you can add a validator and just set a property that enables clientside validation. You can localize the errormessage. The localization works clientside and serverside.
There is no out of the box clientside validation in MVC and you need to find a way to localize clientside errormessages.
Localization itself is different. Ressources obviously by default dont exist per page, because there is no page. But there is a good way to have ressources per view.
I still did not check, if it is possible to set SSL-required per folder.
EDIT
The story is different with MVC3. There is a good validation support now.
There are still things that are not implemented in MVC. The biggest issue for me is a complete implementation for donut cashing and partial cashing. There is some improvement in MVC3 in this area but it is still not complete. Anyway stay tuned: the MVC team seams to be aware that this is something they should work on.
The big one is Controls. User Controls are not available with ASP.NET MVC. I have even gone so far as to try using code like this:
new Label().RenderControl(...ResponseStream...);
No dice.
Of course, as a part of that, there is no need for view state, so that isn't in there.
Server controls do work, though.
As Marc said, third party tools and (serverside) webcontrols cannot be used. So slapping something together quickly by dragging and dropping a few controls on a form (like a grid and a dataaccess control) is no longer an option.
But with the codegeneration etc. you can still make something quickly. And you still have the above option if you need something quick.
I think view-state is non existent in MVC. You will have to track your own view state in some other way than the built in view-state in non MVC projects.
EDIT:
According to comments: "Getting rid of ViewState is an advantage not a disadvantage". – Craig
ASP.NET Ajax is not working with ASP.NET MVC so no UpdatePanel (due to lack of postback). Fortunately there is built-in ajax (Ajax.Form) which can be used to perform partial updates not to mention jQuery which is shipped by default with the Visual Studio project template.

Resources