Way to keep state in MVC2 without Session or Query string? - asp.net-mvc

Is there a way to keep information between post backs in MVC2 without utilizing Session variables or the query string?

You mean like the view state from .NET Web Forms? Technically there is, although it isn't recommended - you're much better off utilizing models and posting the model data to the server and pushing the model back into the view.
This will work well but if you're needing something as stateful as the WebForms ViewState, I would recommend doing your project in WebForms or use the session to save your models.
Edit: Build your form that posts (or gets) data back to the same page. Then in your controller, have a method like this.
[HttpPost]
public ActionResult LoginUser(LoginViewModel model)
{
//work on the model here
return View(model);
}
This will push the form data that the user just submitted back into your view. Then have an Html helper like this in your view.
<%: Html.TextboxFor(m => Model.Username) %>
There are a slew of excellent resources on the web about using html helpers with models. Google around and you'll come across them.

You could use Hidden Form fields to POST the values back to the server with each form submission.

Other alternatives include a cookie or Http Cache - what is stopping you using session?

As a high level concept, you should rely as little as possible not only on Session to store your state, but on statefulness in general in a web application. The idea is that the web itself is stateless by design, and when designing software on that paradigm the software should be designed to embrace a stateless nature.
More specifically, using a ViewModel gives you a strongly typed representation of the data needed for your view to pass down to the client. Pieces of that data which hold information about the state of a given request which can be made from that view can be added to the view in probably a number of ways, but the two most immediate ones are:
As hidden form field elements
As parts of URLs for requests
Check out the NerdDinner tutorial for a standard approach to using either ViewData or a strongly-typed ViewModel. Some Google searches will, as always, yield more information and tutorials. But note specifically where the tutorial uses the ViewModel properties in the view. These can be used anywhere in the rendering of the HTML, either in the HTML helpers or in manually constructing the tags.
Additional interesting reading regarding the statelessness of the web (and this whole not-as-new-as-many-people-seem-to-think REST thing) is the article: How I Explained REST to My Wife.

If your main issue with the Session variables is of a practical nature (want something that works for a single request, not needing to worry about cleaning it up etc) rather than a requirement to not use Session then use the TempData dictionary. It deals with putting information in the Session for a single request only and the framework will automatically remove it for you afterwards.

Related

Razor templates, views and angular.js

TL;DR
What are the best practices when using .NET Razor views and AngularJS?
Context
We are developing a public website (not an intranet application) using mvc4 with razor, and we weren't very familiar with client script, so we started with what we knew: jQuery.
But now things are getting more complicated and we'd like to switch to AngularJS.
On the .NET part, we use Razor templates and UIHintAttribute (plus some custom ones) to render the right html "control". We also add custom html attributes to give extra information to the jQuery part (like title for a tooltip....)
So we already use a declarative way of setting the user interface behavior, that's why AngularJS seems a good option.
Questions
Since we already have models defined server side, and since AngularJS also uses models, wouldn't it force us to duplicate code?
How do we deal with data binding feature, since we already do some binding server side (in the views). Should we make a completely asynchronous application, making AJAX calls from AngularJS to load data, or can we mix both?
Anything else we should be aware of when trying to use both of these technologies?
I did some research on Google, but I can't find detailed ways of mixing Razor views and templates with AngularJS... Perhaps that's just not a good thing to do?
We dealt with this issue for months when working with MVC plus another JavaScript framework (Knockout). Ultimately, if you're going to be using a client-side MV* framework for rendering your user interface, you will find that mostly ditching Razor is going to be your best bet.
Most of the major MV* JavaScript frameworks, including AngularJS, assume you will be maintaining UI state and rendering your user interface based on JavaScript models or view models. Trying to mix in server-side rendering is just not going to work very well.
That's not to say there is no use for MVC when it comes to developing an Angular application. You can still take advantage of some great features like ASP.NET Bundling and Minification. And sometimes it works really well to embed JSON directly into the page using a Razor view or partial as opposed to making an additional AJAX call.
As for models, you may want to take a look at Breeze.js. It's a JavaScript library for data access that goes great with ASP.NET on the server side to share model metadata.
We wrote our own data binding mechanism that synchronizes the angular.js model with a view model on the server side. The javascript model is generated from a JSON serialization of the server-side view model to avoid the duplicate code that you were talking about.
We are using SignalR to update the client's view model from the server.
Server-side changes of the C# view model properties are sent to the client as a packet containing the path to the property, e.g. Persons[42].Address.City, and the value itself, e.g. New York. The view model inherits a base class that takes care of generating the property path, so the actual view model looks quite clean and we can concentrate on business logic.
Client-side changes of the javascript view model properties are sent to the server in the same way. To catch the change events, we encapsulate all fields of the original javascript model in get/set properties where the setter sends the update packet to the server.
Server-side methods of the view model can be invoked in a similar way. All objects in the view model have an invokeMethod function that can be used like this: Products[42].Manufacturer.invokeMethod('SendEmail', 'mailsubject', 'mailbody'). This will send a packet to the server containing the method path Products[42].Manufacturer.SendEmail and the arguments as an array of ['mailsubject','mailbody'].
In conclusion, the html view (kind of) binds to the view model on the server side where other systems, such as regular Razor views can work on the same objects.
The source code can be found here: SharpAngie.

ASP.NET MVC 2 user control caching

I've recently decided to try out MVC 2 and coming from a webforms background, I'm having a little trouble trying to figure out the best practice solution to caching data provided to a partial view (user control).
In my webforms application, I have an AccountSummary.aspx page, which has a Booking.ascx control. Booking.ascx had output caching of 300 seconds and in the Page_Load of AccountSummary.aspx, I used to check if the control was null, and if not, pass it a UserId. Then in the code-behind of the Booking.ascx, I used to make a data access call to fetch all the bookings, thus a call to fetch the bookings was made at most once every 300 seconds.
I would like to achieve the same in MVC2, but I can't seem to find the best way of achieving this because all the examples on the web seem to pass the data to the user control in the RenderPartial HTML helper method (which I don't want because on every page load I would have to pass the booking info which is going to kill my database!)
Please advise :-)
Cheers, A.
There is no simple mechanism for view-level caching in ASP.NET MVC 2.
There are some clever tricks to exploit the output caching in ASP.NET, like Donut Caching and Donut Hole Caching, but they both violate the MVC pattern (by making the DAL spill over into the views, for example), are very tricky to get right, and exhibit virtually undocumented behavior. (See the comments in the blog posts and other posts here on SO for more information.)
The short answer is that view-level caching (i.e. caching a partial view or a view, as opposed to an action method) is a trip you do not want to embark on if you are new to ASP.NET MVC. Hence, you should cache in your DAL instead, or on your action methods.
In your example, you could have a OutputCacheAttribute on an action method that returns a partial view with the booking list, or you could use the System.Web.Cache to cache the booking list when retrieving it in your DAL.

MVVM ViewModel vs. MVC ViewModel

ViewModel is a term that is used in both MVVM (Model-View-ViewModel) and the recommended implementation for ASP.NET MVC. Researching "ViewModel" can be confusing given that each pattern uses the same term.
What are the main differences between the MVC ViewModel and MVVM ViewModel? For example, I believe the MVVM ViewModel is more rich, given the lack of a Controller. Is this true?
A rather challenging question to answer succinctly, but I'll attempt it. (Bear in mind that the answers to these kinds of questions are still the subject of debate amongst developers.)
In MVC, the ViewModel provides all the information necessary for a View to be rendered. The data it contains is created using data defined in the Model. The View reads the ViewModel and renders the output. Input from the View is passed to the Controller, which manipulates the Model, constructs an appropriate ViewModel, and passes this to the View for rendering.
In MVVM, the ViewModel serves the same function as it does in MVC, but it also replaces part of the MVC Controller by providing commands which allow the View to manipulate the Model. WPF databinding manages the updating of the View according to changes in the ViewModel (and this effectively replaces the remaining function of the MVC Controller).
It's been a while since I played UI Design Patterns Bingo.. however let me take a stab at this..
MVVM is just something that MS has come up with... because it helps you to get the most out of WPF. You combine the state and behavior of the view into a class (a presentation model) that is easily testable + then you use data-binding to get the data into any view.
This link has a brief of the evolution of MVVM. Combine this with Fowler's "GUI Architectures" series, and you should be on your way.
Update: Didn't know there was something called MVC-VM. Apparently a brainchild of the ASP.NET MVC crowd. Looks and sounds similar to MVVM (except tuned for ASP.NET MVC); the only difference is that it places a restriction that there is 1:1 mapping between VM and View. I'd have guessed 1:N, but everything else matches.
I know this is a (way) old question, but I've been pointed to it as an example of using "View Model" in the context of MVC. I argue that this is incorrect and can lead to confusion by people who are new to either/or/both patterns. Whoever is doing it--stahp. Here's why (and it's even an answer to the original question in a roundabout way).
An example of when this happens can be seen in this question. The user is trying to use a View Model that implements INotifyPropertyChanged in an ASP.NET MVC application, thus mashing together desktop and stateless web application design in an architectural fail and heartbreak.
To put it simply, there is no "View Model" in the MVC pattern. There is, however, a functional equivalent, and that's the Controller. Just to be clear about the parts and their purpouses,
MVVM (desktop applications):
Model - Strongly typed object that holds data to be passed between the View and View Model
View - The UI viewed by the user and through which the user interacts with the system
View Model - Interprets user actions (e.g., via ICommand), performs them, updates application state
MVC (web applications):
Model - Strongly typed* object that holds data to be passed between the View and View Model
View - A UI generator that combines the Model, code and HTML to render a webpage
Controller - Accepts user requests, interprets them, updates application state and uses a View to convert this state into an HTML webpage
The Model is practically the same in both patterns. Desktop models may implement update event notifications, web Models may be dynamic (i.e., not strongly typed), and both may or may not include validation methods or metadata.
The View in the desktop is what the user sees. In the web, it is a generator that outputs HTML for browsers to display on the client side. It must interpret user interaction on the desktop, but on the web that is handled by client side javascript, the browser, and the requests that are sent back to the server.
The View Model/Controller are roughly functionally equivalent, but differ greatly in how they are implemented and how they operate. In the View Model, user interaction with the application is transferred to View Models via ICommands, routed events, and other methods (many MVVM frameworks provide different ways to hook View Models to the UI and other parts of the application). In a Controller, a request comes in with all information needed for the Controller to return a result to the user (assuming it's a 200 OK request). The Controller must perform whatever work is necessary to create the state (aka Model) needed for the HTML generator (the View) to create the response. Design-wise, the Controller sits above the View and Model knowing and controlling both, whereas the ViewModel sits next to the View, passing the Model (and other information) between them.
What really seems to confuse some people is that there are client side MVVM frameworks that you can mix into your MVC application. These exist solely in javascript in the user's browser, and have nothing to do with whatever particular pattern you're following on the server side. You can run a classic ASP website that uses MVVM on the client side. Hell, you can run static HTML pages that use MVVM on the client side. They are that separate.
These javascript MVVM frameworks typically follow a similar pattern to the desktop MVVM pattern described above, but adjusted to work more in tune with the nature of the HTML DOM and javascript. For example, there is no extensive binding system woven into the DOM, and javascript has a very limited type system, so matching up templates to models is much different than in WPF. They also typically work disconnected from the server, and when they need to interact, prefer AJAX calls rather than POSTing the page back to the Controller (AJAX calls typically are handled by WebAPI Controllers in ASP.NET MVC).
So, to summarize, there really isn't a View Model in MVC. The Controller is the rough equivalent, but is very different in how it receives user input, interprets it, and returns a result to the user. Using the term "View Model" to refer to anything in MVC can only lead to confusion, and therefore should be avoided. Use the proper terms for the proper parts of the pattern. It may seem pedantic, but it should help keep things clear and be less confusing to people who are new to both patterns.

Building a complex page in asp.net MVC

I am currently considering the best way of building a relatively complex page in asp.net mvc. The page (and pages like it) will contain numerous 'controls' such as a shopping basket, recent news widget, login controls and more. In other words, it will be very component based.
My question is, what is the best way of building something like this in asp.net MVC? In regular webforms the answer would be simple thanks to user controls and the fact they can be nicely self contained. In MVC, I understand that in theory I should probably build a viewmodel that includes all the data needed for all my widgets and then render partial views in whatever page I'm building.
Could an alternative approach be to use javascript to load widgets 'dynamically' (think jQuery load) by simply calling into controllers that render partial views. That way I could have a basket controller, which when called renders out a basket. Of course, this relies on javascript....
Whats the best practise for situations like this?
Thanks
You could of course use JavaScript to populate the page sections but then this content will not be accessible to search engines (but that probably does not concern you).
What you need to understand that there is currently no way to make these partial views perform independently. Like talking to their own controller and posting data while having the rest of the stay unchanged (like it could have been done with WebForms and user controls). If you think postbacks and control state these things do not exist any longer. Your "control" makes a post, the controller has to process the request and then recreate the complete view along with all element values, states and other "user controls".
Unless you do it asynchronously with JavaScript of course. But then it's not gonna be an accessible page any more.
You can try SubControllers from MvcContrib or Steve Sanderson`s "Partial Request" approach.
But i warn you - communication between (partial requests, i haven't tried subcontrollers myself) them might get tricky and lead to mega failure. Use them only if you are completely sure that they are completely independent.
Anyway - that's a bad idea and should be avoided through controller/viewmodel inheritance or something....
My understanding of MVC is not yet up with WebForms, however is the generally accepted approach for stuff like this to simply throw these things in the ViewBag rather than include them in the ViewModel?
You could send down a main view model with some simple checks on it. Then render the appropriate Action if required. Then each partial could use it's own viewmodel and you wouldn't need to send everything down initially on the same viewmodel.
Razor:
#if (model.ShowShoppingCart)
{
#Html.Action("Index","ShoppingCart")
}
#if (model.blah)
{
#Html.Action("Index","blah")
}

Asp.net MVC with ViewState?

Just read blog post of Maarten Balliauw.
Wanted to ask will
<%Html.Serialize("person", Model); %>
return bunch of 'don`t-stop-debugging-heavily-server-sided' RAD controls?
Is that's a good idea to include this?
If so - what kind of usage would be appropriate?
I view it more as a way of avoiding using the session to transfer data between actions than viewstate per se, and that's what I would use it for. Seems to me an ideal way to implement some wizard type functionality in which you want to carry the data forward through a series of actions before you persist anything to the database. There is, of course, the danger of overusing it I suppose, but as long as the framework doesn't automatically impose it on you, then I don't see the same dangers of viewstate popping up. With viewstate, you had to jump through hoops (and potentially break other things in the process) to avoid it.
We shouldn equate Base64 encoding with ViewState. I don't see the state of the view being serialized in that snippet. I see the state of the model. So describing that as ViewState For Asp.net MVC is very misleading.
Also consider this is opt-in and not automatic in any way. It's primary usage will probably be for optimistic concurrency as well as Wizard UIs where you want to store the users previous selections in the view as opposed to the Session or Cookie.

Resources