How do I create composite views in ASP.Net MVC 3? - asp.net-mvc

How do I create a view in ASP.Net MVC 3 that defers creation/rendering of a portion of the view to another view/controller, without knowing at design time what view/controller will be deferred to?
I have a Dashboard view/controller that uses a Layout page. the dashboard view does most of the work of rendering the overall screen. However a certain placeholder section of the overall screen will differ based on business rules, configuration, user interaction etc. There are three separate plugin views/controllers that may need to be rendered in the placeholder section. How do I instruct the Dashboard view to render a specific plugin view once the Dashboard controller has determined which plugin should be visible. I have accomplished this already by putting flags in the Dashboard model and then having conditional logic in the Dashboard view call Html.RenderAction with the appropriate parameters based on the flags. This seems unsatisfactory and I would assume there is already a simple built in functionality for this kind of scenario, please advise.
Thank you

You are really asking "how do I dynamically render partial views who's identity is known at design time."
One can get there two ways, either through Html.RenderPartial or Html.RenderAction. And both have their place. If the main page "knows" enough to have the view data, then RenderPartial is your the better bet as it is a bit more efficient than RenderAction. If you only know, say, a unique identifier for your portal widget than RenderAction works because you've now got a fully capable controller method that can do things like go back to a database and render a view.

You could write your own htmlhelper and use that in your view instead of using the flags.

Related

Developing web applications with widgets (or re-usable components) in ASP.NET MVC

I have experience in writing code... but new to developing web applications.
I am in process of choosing a framework for my project. Based on my initial research almost everything is very VIEW centric where after all business logic has been executed a model is populated with data and passed on to the VIEW.
So the lowest level of granularity is the VIEW.
But I wonder what is the right technology to use if I wanted to develop re-usable widgets or controls. and then reuse them across multiple VIEWS.
i would prefer if the controls are in JavaScript and then they can easily be reused across pages. (so no asp.net server controls or web forms).
So if I were to select ASP.NET MVC 4 ... does it have anything to help me write code in reusable widgets... or will it simply ask me to write the VIEWS which work with the data provided by the model?
Sorry if this is newbie question
to eloborate on what I mean by a widget.
Suppose I am writing a discussion forum web appliction. I want to write a widget called post which has 3 views. View 1 is edit mode. View 2 is summary mode. view 3 is Detail mode.
I throw in this widget in a page called QuestionStream and in this page the widget appears in summary view. I perform data binding so that i get a list of questions.
I throw in this widget in a page called ThreadView and in this page the widget appear in detailed view. I perform data binding and I get all the details of the question.
I throw in this widget in a page called NewQuestion and in this page the widget appears in edit view.
So its a self contained control... but is reused in multiple places in different modes (so to speak).
Here is summary list on how to create reusable components/pages/widgets in MVC. There are many more ways, these are just examples to give you starting point on what to look for or how to make one.
1. Partial Views
Typically used for breaking down large views, into smaller views then combined at runtime
View-centric approach, the controller can choose a View to generate.
Tutorial
2. Render Action / Render Partial
Invokes an child ActionMethod directly in the view page as inline
expression.
Useful for partial views that requires a business logic.
3. Custom DisplayFor/EditorFor Templates
Model-centric, which means they take model metadata (Attributes/Annotations).
Cool tutorial
4. Custom HTML Helpers
"Commonly used to generate boilerplate HTML" (LINK)
The following link shows how to create page "widgets" in MVC. The author doesn't mention "widgets", but it is the same as you are looking for.
http://www.mikesdotnetting.com/Article/105/ASP.NET-MVC-Partial-Views-and-Strongly-Typed-Custom-ViewModels
Based on the tutorial mentioned, below is the image on what it should look like (notice the "Most Popular" section, that widget is completely reusable across all pages)
ASP.NET MVC 4 has the ability to write methods that are re-usable. The View is expressed in mark-up (typically) and will call methods from the Controller to populate the View.
To be honest though, even though you're asking a very simple question, I think what you're trying to get at is the re-usability. All the technologies you listed: server controls, web forms and mvc4 have that capability. It all depends what you want to do.

MVC partial views, partial model, partial controller?

Currently i am investigating if MVC is the way to go for the new major version of our web application. We have an existing web application with webparts, dynamically rendered according to some user settings. Each webpart has its own data and own logic (for example, one webpart with user information, one webpart with currently logged-in users, one webpart with appointments etc. etc.).
What we need to accomplish (i think) is to render a single view, which contains several partial views. Each partial view represents a different model, and has its own logic.
I figured out how to put multiple partial views within a single view, but i don't know how to handle the business logic for each view (in "partial controllers"? if possible at al?), and handle the model for each view?
So the main purpose is to render a page with multiple dynamic views (according to what the user has configured), each with its own logic and data. And then when, for example, a button is clicked in a partial view, the corresponding controller is called to handle the event, and returns the updated partial view. The partial views need to be loosely coupled, and updated async.
From what i've seen so far the most tutorials and documentation are focussing on MVC in general, not on how to separete the business logic and model for eachr partial view.
So I'm not asking how to do this, but:
Is it possible to easy accomplish this with MVC 4 or 5?
Does anybody know a good real-life example or tutorial about this?
I hope anyone can point me in the right direction or share some thoughts on this...
You could make one or more controllers with an action for each webpart.
Group all related webparts in the same controller but make an action and View+ViewModel for each webpart. Then use the Html.RenderAction method to call these actions (and have your webparts placed) on your page/main view.
DISCLAIMER: This said, each call to Html.RenderAction creates a complete mvc flow, instanciating a controller, model and view and finally renders the whole thing and passes the value to your page/main view. Having lots of Html.RenderAction has the potential to slow your page creation a lot. You could look into DI/IoC like Unity and consider reusing controllers, or just look into System.Web.Mvc.DependencyResolver to handle the creation of controllers yourself.

Maintaining input control state in MVC

In the app I'm working on the administrator has the ability to select a customer to work with in a drop down list. Thing is that there are a large number of views that the administrator can go through and each time they'd have to select the customer again. In webforms this was rather easy... store it in a Session variable and reset it when another page loads.
MVC not so much. I seem to be stuck at the point where I pass this value to the view from the controller. We are storing the value in a Session variable which we access using a base controller like this:
MyController.CurrentUser.CurrentCustomerId
The question I can't solve is how I pass this value to a partial view. The customer selector tool is in a partial view which is added to pages that need it.
I thought of using the ViewBag, but that means that in every single action in my controllers that requires this value I would have to add:
ViewBag.CurrentCustomerId = CurrentUser.CurrentCustomerId;
And even then I'm not sure if the ViewBag data is carried through to the partial view. I think it is.
Seems like there should be a more efficient way to do this and still abide by MVC rules?
#Andre Calil provided a very good solution for carrying user information between controllers and views and I ended up using this approach.
See his answer at the following link: Razor MVC, where to put global variables that's accessible across master page, partiview and view?

ASP.Net MVC - Designing Views for Premium (Paid) Version

I have a service that is currently given away for Free!
Im now reaching the point where I have enough clients that I want to offer them a "Premium" Version.
So, some of "premium" features will include some extra text boxes on views.
I've built some custom attributes to handle security on the controller, but whats the best way to handle the view?
Should I create another view and present either the free of premium view?
Should I only have a single view? (if so how would I handle showing only certain text boxes\areas)
Suggestions and samples welcomed.
One option would be to make your main URL's very simple, and simply have them render a child action based on the membership level of the user.
Using HTML.Action() you can completely render a different view, and simply have your view look like this:
#model mymodel
#User.IsInRole("Premium") ?
Html.Action("PremiumView", "MyController") :
Html.Action("NormalView", "MyController")
If you have parameters, you can just pass them along.
Also, make sure you mark those subactions as Child Actions, using [ChildActionOnly] so they can't be accessed independently.
This way you can keep your free and premium versions totally separate but keep the same URLs.
You could also use Route Constraints to route to different controller actions based on various factors such as membership level.
You could create a custom view engine that supplied premium content when applicable, then name your views according (e.g. MyView.cshtml & MyView.Premium.cshtml). This gives you the flexibility to extend views with premium content while also not committing yourself to a major change up-front. You'll also need to validate when and when not to accept "premium" changes in the actions, but that should be simple role checking when you go to process.
If your views contain more controls than your models are different and therefore your controllers are different, too. Your paid version may evolve at the different pace than the free version so I would suggest you keep the code separate.
This seems like it would be best done on a per-view basis. If the free vs premium views are mostly the same with a few differences, then I would suggest using partial views within the main view checking the membership status for altering the display.
If there are major differences in the views for UI and functionality, then you might look at swapping out a different view entirely within the controller.

ASP MVC banner rotator

For my site I want to implement a banner control that will be on the left side of the site.
The banners will be stored in html in the database and each one will have a rating. Then using the rating each one will have a number of occurrences (percentage).
Do you think that there is a feasible solution to put all this flow in a separate dll? Is that even possible in the mvc architecture. I would prefer to do it as a partial view and have everything in a separate dll the partial view and the data access layer. Do you think that this is a good solution?
What is your approach when you have to implement a "user control" (partial view) ... do you put it in the website project or a separate project?
Is there any other way to implement this instead of using a partial view?
Thanks, Radu
There's a few choices that you have-
do it as a HtmlHelper extension. Probably not ideal for this kind of thing as the managementof the banners to display and the associated logic is really the concern of the banner component/widget/partial.
Do it as a partial view and use Html.RenderPartial(object Model) to call it. Now the logic is in the partial view, but there may also be some application logic that shouldn't really be going into the view and really belongs in the model or the controller. Also, you can end up with fat view models being passed to the main view that have to also carry a view model for each partial rendered in the main view. I think in some situations this isn't ideal, particularly when the data in the view models for the partials has nothing to do with the data for the main view. Which brings us to...
Do it as a child action with an associated controller and partial view. The logic will be nicely encapsulated in the controller and the partial view will simply render out whatever it's passed from the BannerController.
You could certainly put this in a separate assembly and set it up as a Portable area. This way, you can embed the partial views in the assembly and to reuse the widget would be a case of just dropping the assembly in the bin folder and referencing it in your main application project (you may also need to set up some configuration perhaps).
Whether I would personally do it this way or not depends on reuse for the component; to be honest, I'd probably set it up inside of an area in the main application to begin with and then, if I find that I need to reuse it, move it out to a portable area.
I also generally like to keep the data access logic in a separate assembly and use the repository pattern along with IoC to inject repositories for doing data access into controllers.

Resources