Synthesize multiple action methods in MVC - asp.net-mvc

We have a dashboard-style application with lots of individual bits of the screen that load asynchronously. Each of these bits really makes sense as its own action on the page's controller. However, the data will load more quickly if we reduce the number of http requests to 1. I'm considering creating an action that just returns a combination of results from several smaller actions, such that the web client can GET the actions separately or together. However, this seems like a hand-rolled solution to a common problem, so I'm wondering if there's built-in support for agglomerating actions in this way that I don't know about. Anybody?

In your core view, you can use the Html.RenderAction() method to render completely separate actions from another action.

Why don't you just use ViewModel containing all data needed for your dashboard and then create several partial views, feed them with data from ViewModel?
I have also an dashboard in my project, I did it this way and I am happy with the solution. I have DashboardController and its Index action just takes ViewModel (which aggregates all necesary data) and sends it to View. In that View, I have several partial views (each of them needs its own model) and I pass them data from my ViewModel. Inside that partial view are then references to specific actions (like CRUD for specific models).
When you do it this way, you can easily create partial views for specific models (Task, Project, User .. in my case). And then just use them as a pieces in your final layout. My ViewModel contains collections of Tasks, Projects and Users which I then simply pass to matching partial views.

Related

Multiple Views Same Model

I have a Course Model which goes the controller and views in a restful way.
For my Course show, it is fully featured. I now want another Course show which will have a simplify page and it like to the original course show.
How can I implement this? I want it to be restful, so in my controller there should only be show, update, index, etc.
Should I create another controller that have an different name from the Model? E.g. Course2?
If it is an admin view vs. public view, I would have entirely different namespaces for two different RESTful controllers. Or if you think you're going have this summary vs. full view thing a lot, create namespaces based on that distinction.
Another option is to encoded the differences in a single ERB template. Or you could actually have the show action render different templates from the same action using some conditional logic.
Without more context though, I can't really say what's the best option. I am personally against creating non-RESTful actions unless it's really going to be a one-off thing. Non-RESTful actions tend to get out of hand in my experience and controllers can get really ugly and unintuitive.
If this is truly just displaying a subset or a different arrangement of the same information, then I think this is a job for the view. At most the controller can use the same action, but select a different view to render, such as might be done if the user wanted to see html vs plain text.
The controllers job is to interpret the model and the views job is to collect and display information. I think you would be concerned about the view having logic in it if you what you describe as a "summary" were more than just a subset of the info, for example if you started to calculate the distances being traveled or how long it would take or how much it would cost based on the data that is provided, then that would be bad.
So I this is just a subset, then I would suggest either rendering partials based on some variable set by your controller, or if organization of the display needs to be substantially difference, then the controller can select a different template to render.

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 should we pass a data to a view in a big ASP.NET MVC web site

First of all, I have been a php programmer for a long time and I am a mvc programmer newly. I did a few minor web sites that each have one or two controller at most. But I've started a website that will be very major web site. There will be a lot of data to pass to views.
Now, normally I try to use model approach every time instead of ViewBag or ViewData approach. If the view demands more data, then I change the model class and then recompile the project. Especially, if the topic is an index page, the data to pass to the index's view changes every time. In a big web site, I'll use a lot of partial view that uses different models. So every time, I will have to change the index's model to support those partial views in the index view. if I add a new partial view into index view, I have to add the partial's model into the index's model.
I implement an IndexModel class for an index view every time when I start a website. Then I add properties to this model every time when I add a new partial view to the index.
Now is this a correct approach or should I use ViewBag or ViewData for partials' models. I think the real question is when we should use the model approach and when we shouldn't...
If you share your experiences, I would be grateful.
The MVC approach you should use always, especially for simple sites, it's save your time and make application more understandable.
If you write something larger than two pages, you need to use MVVM pattern (growth of MVC), in that case you will escape from using "partial models" with ViewModels.
Model must contain only busines logic.
Be better if you will always use ViewModel (not a Model) for returning data from a view and pass it to view, because it provides some safety.
For facilitate the procedure of copy data from Models to ViewModels use the things like AutoMaper and EmitMapper.
ViewBag and ViewData you should use only for additional data's like item colections for DropDown, or some view-text like page title.
One more advantage of MVVM pattern is better testability. If you write and support really hugh site you may write tests for some responsible parts of code.
For more details you can look at google - MVVM, ASP-MVC.
If i something not understad in you question or miss, write it in the comment ("add comment" ref).
I personally prefer to keep my sites consistant and always use Model + Viewmodel (no matter how big the site is) despite the extra work (which isn't much anyway).
It helps with maintainability. I know where and how everything is stored and coded into the site.

Is it considered bad practice to write db queries in a controller rather than a model

I've read that best practice dictates fats models, skinny controllers.
Models should contain business logic such as getting a list of customers based on parameters sent from a controller.
Controllers should contain just enough logic to invoke methods within a model to return to a view.
However I see many examples and tutorials where there is logic within the controller such as a query that accesses a db to get a list of products. I was under the impression that the logic should live in a method inside a model. The controller can then invoke this method, rather than containing the actual logic to query the database.
So if I have a ProductController I might have a Index action which returns an Index View, and I would have a ProductModel which would house my logic to display certain products based on a query string(which the ProductController would pass to said model). Right?
So if I have a ProductController I might have a Index action which returns an Index View, and I would have a ProductModel which would house my logic to display certain products based on a query string(which the ProductController would pass to said model). Right?
That is correct. As per the Model-view-controller architecture:
The model manages the behavior and data of the application domain,
responds to requests for information about its state (usually from the
view), and responds to instructions to change state (usually from the
controller). In event-driven systems, the model notifies observers
(usually views) when the information changes so that they can react.
The view renders the model into a form suitable for interaction,
typically a user interface element. Multiple views can exist for a
single model for different purposes. A viewport typically has a one to
one correspondence with a display surface and knows how to render to
it.
The controller receives user input and initiates a response by making
calls on model objects. A controller accepts input from the user and
instructs the model and viewport to perform actions based on that
input.
Keep the data-related queries and operations in the model; stuff as much as you can in there in accordance with DRY (Don't Repeat Yourself). Make the functions reusable as much as possible so they can be ported into various controllers and used throughout the application as necessary.
The view should contain little - if any - logic outside of view-specific work.
Your controller functions should invoke the model functions required to retrieve and manipulate data, and should be as "thin" as possible (as you pointed out). The smaller and less involved the controller, the easier it will be to add asynchronous features that "don't reboot the application" on the front-end, making for a better user experience. (If you are concerned about this, anyway!)
The Add Controller dialog box in VS 2010 has the option of adding a scaffold with CRUD functions into the controller. This should tell you quite a bit above how the ASP.NET MVC dev. team views this debate.

best practice for what is in a ViewModel

I am wondering if it is a good idea or bad, placing things like a List of countries in ViewModel, for binding to a drop down list? For example on a site's Registration page.
I was under the impression that a ViewModel is supposed to represent an instance of the filled out form, but I think I may be wrong as I have seen other people put things like lists in their ViewModel.
Would it not be better to put it in a static class somewhere and called directly from the View?
Like CommonData.ListCountries(); and then using Lambda to convert to SelectList item list in the view Directly?
As you've realized there are a variety of ways to accomplish your goal. While the MVC design pattern encourages certain application organizations how you organize your models, views and controllers is ultimately a matter of preference.
Scott Allen discusses his preference for dealing with ASP.NET MVC drop down lists in a blog post. Scott uses an extension method to convert an enumerable of a complex type into an IEnumerable<SelectListItem> on his model. He then describes that upon post back ASP.NET MVC will not be returning the IEnumerable<SelectListItem> he sent to the view, but only the value the user selected. He then suggests that utilizing two models can simplify things.
This is a reasonable description of what I refer to as ViewModels and FormModels. A ViewModel carries the display data to the view and a FormModel is used for carrying collected data back to a controller action. To explain further:
ViewModels contain data that help render views. By organizing my ViewModels this way I can place all necessary information to render a particular view into an associated model. This prevents me from having to use ViewData for anything that's not truly temporary.
FormModels are used to gather user input. FormModels (almost) never contain references to other complex types and are made up of primitives, DateTimes, and strings.
In either case I have a hard rule to never reuse a model for a different view. Having your models closely aligned with the views used to render them makes your views easier to write. You don't have to worry about things like static methods because your models should be carrying data to their associated views in a form that is easy for them to render. Tools like AutoMapper can help "flatten" domain objects into models for display purposes.
For additional reading checkout: ASP.NET MVC terminology is tripping me up - why 'ViewModel'?
Whatever data your View needs, put it in the ViewModel.
The way i see it, once your view is going through the rendering process, it should have all the info it needs from the Model it is bound to.
If you start to use helper methods, then the View is "going back to the controller" in a sense. Extension/helper methods are fine for formatting, etc, but they should not call through the model.
Don't forget, you also have ViewData (basically HttpContext.Current.Items, lives for single request), which is a lightweight storage mechanism that can be used to share data across partial views (for example).

Resources