Display & Update Cart Count on an MVC Layout Menu - asp.net-mvc

I have an MVC application which is supposed to show a Shopping Cart Count on the primary _Layout page. I need to update this value as users add or remove data from their cart. Since these data changes can be done from multiple locations throughout the application, I'm hesitant about putting GetCartCount() calls on each and every controller out there.
I was considering using either a ViewBag or a knockout computed observable to store this value in, but I'm open to any other suggestions.
What is the best way to store & update a single value that will be used on a layout page in an MVC application?

The simplest way would be to put this count variable in the Session and output it directly inside of the _Layout.cshtml using #Session. If you don't want to use session you can put this count variable in the ViewBag with every request, you can set it in the BaseController(if you don't have one just create one and inherit your controllers from it) in OnActionExecuting method and you will avoid duplication.

Related

Accessing session data from a layout

In my ASP.NET MVC solution I have a number of services.
One of them, SessionService, is used to access the currently selected region and time span.
I want to display those in a layout used to decorate views. What is the best design approach to access those values which are stored in the SessionService?
Right now I'm thinking about using calling a ChildAction from the layout which in turn calls the session service:
_Layout -> aController.ChildAction() -> SessionService.GetRegion()
Is it a good approach or can you recommend anything better?
UPDATE 1:
Other options for passing the values that are possible:
via ViewBag
via ViewModels
However the drawback for these options is the fact that it would be necessary to populate them in each and every action method which would lead to duplication of code (which could be mitigated by means of a filter, but again this will require decorating controllers with the filter).
UPDATE 2 (born in the discussion with O:rvar below):
Another option is to create a base controller which will be populating ViewBag properties upon creation. All other controllers should derive from it.
You should be able to access you session data in the view with the following code:
var region = #Session["Region"].ToString();
Or you could call the controller method as you mentioned with an ajax call and get the session data that way. Using the childaction approach is also a fine way of accomplishing what you want.

MVC embed data in Master Layout without violating standards

I have a master layout for a conference registration system, what I'm trying to do is to display the number of registered users in the master layout.
What is the best way to do that ?
I can call a static method to get this count, but from my knowledge, this is a violation of the MVC standards, because interaction between a page and the server should be only through Controller/Action method.
So what is the best way to do this ?
When I need to display data in the layout page, particularly if it's a small amount of data, I usually put that data into ViewBag/ViewData. Otherwise you need a base class model that every developer has to remember to inherit from to carry the data into the view. The ViewBag/ViewData can then be populated by an OnResultExecuting filter on the base controller class.
You need to have main Model/ViewModel for all of your pages or use two or multiple Models/ViewModel in targeted pages. In this way you pass all required data to view via controller methods perhaps by calling a static method in methods. see the following articles to employ the above techniques:
Two models in one view in ASP MVC 3
Multiple models in a view
Another way is storing related data in ViewBag or ViewData Dynamic types in controller methods each time needed and then prepare and use them in View. Note that using them should be avoided in favor of using strongly typed ViewModels.
cheers.

How to pass data from one view to some other view in MVC 4.0?

I need to pass data from one view to another in MVC 4.0. I am new to MVC 4.0.
The scenario is that I have a View in which a combo box is populated when the view gets loaded. I have a form on this view and on submission of this form I need to do some processing and accordingly show some status message on the View.
Since HTTP is stateless protocol the data (with which combo box got populated) gets lost. I want to retain this data as I don't want to do same processing again and again to fetch the data.
Please suggest me how can I proceed?
In MVC (although I don't think exclusively) you can use the Session class to store variables across multiple views.
You can add an object to the Session array as a key/value pair with Session.Add(), and you can access the data via either an index, or the key.
You can also add a variable by simply accessing the Session index with either the index or the key, regardless of whether you've explicitly added it to the array. So you can do Session[0] = new Object(); or Session["object"] = new Object(); because they have overridden the accessor property.
I would recommend however that you do some research into proper use of the Session array.

Telerik Grid MVC and check all checkbox on all pages

On Telerik demo site we can see an example of how to implement kind of functionality: "check all checkbox in a grid's column". But in my case it has 2 disadvantages:
It didn't check all checkbox on all pages.
It didn't save a state of checkboxes on different pages.
Is anybody know how to resolve these issues? Thanks in advance.
As long as I know there's no built-in functionality to do so. The same problem happens when you select records on page one and change to page two, you loose whatever you selected before.
To achieve that functionality you have 2 options (I've used both on previous projects)
1) On each check make an Ajax call to one of your controllers and store whatever you selected on a Session Variable (This can be inefficient if you have a lot of records)
2) Create a javascript variable and store your selections there, and send back to the controller using a json variable or a comma separated values string
As I said, I've used both approachs so it depends on if this works for you or not
Hope it helps
I can't test this, so I'm not 100% sure, but looking at Telerik's example, one reason it's not persisted is because every "page" of the grid requires a postback, and in the controller action result method, they aren't passing in the model (or view model) for the items that are bound to the grid, they're only returning that list of items back to the view, so it will never "save" which items are checked/selected and which ones aren't. You should be able to get around this by making your view model a parameter into the HttpPost action result method and then passing that list back to the view after the post so that it retains which items are selected instead of creating a new one. This won't solve the issue with not selecting all the items, but it should at least retain which ones are selected throughout the pages. I think the reason for it not working with all items is it can only select the ones that are actually being displayed at the time. You may want to do a post (or ajax) to select "all" items.
One of the major reasons for using paging in grids is so that you don't have to retrieve all of the data from the data store and generate a lot of HTML to push to the client.
It's been my experience that most users understand that a "select all" check box only checks the items on the current page. I've not seen a site where checking such a check box would actually check all records, even those I can't see.
If you have an action which will affect more than the current page of records, I would suggest that you add a button which clearly indicates that the action will affect all records, then send a command to your data layer which will perform that action. This will perform better (you don't have to send a potentially long list of ids across the wire) and allow users to understand the repercussions of their action.

shortterm storage of user selection from form to controller

I am trying to conceive of a way to store a list of selected items to the session, for later use. I've googled and read examples for 2 hours now, and haven't found any examples that work.
The basic idea is this. User sees a list of items to act upon. User selects a number of them. User chooses action to perform. Controller takes list of selected items, and begins to act on them.
Am I thinking about this wrong? It makes sense to me to use an Ajax action to store the 'select/unselect' action on the session object. I really don't want an entire database object to handle this. I just want a simple list of selected objects. In classic ASP, I'd just have reacted to the selected items in a form post, but that doesn't seem right in asp.net mvc....
How do I construct this behavior (with or without the Ajax, but preferable without the DB access)?
I don't get it, why not bind directly an array of bools or something directly to your view's list of checkboxes? You can get them as parameters in your controller function and act upon them directly, with no middleman, they'd just be another POST value.
Or even better when you send in your list of items as part of your model, make them a structure that has a bool selected=false field that is bound to the checkbox next to the label, and you'll get the results back in your model directly.

Resources