First post so please be gentle :)
When creating user controls in ASP.NET MVC, what is the best way to structure the code so that the controllers that invoke views that use the user controls do not all have to know so much about the controls? I would like to know a good way to maintain DRY while using user controls in ASP.NET MVC.
Please note, this question only pertain to user controls that require special handling and logic on a postback. I have no problem creating nice DRY code for user controls that are either view only (using RenderPartial) or that require some pre-processing to create the appropriate ViewModel (using RenderAction).
Also, this question pertains only to achieving reusable controls within an application. I am not worried about reusability between applications at this point.
To give a specific example, let's say I would like to create a 'Quick Add' user control which contains three entry fields, First Name, Last Name and Company Name and a submit button. When the QuickAdd functionality is used, the following steps should be performed independent of what page the control is on:
Validate that the fields were not empty, if they are, show an indicator.
Perform a lookup to a repository to see if the Company already exists, if not; create it.
Create a new contact associated to either the existing company or the newly created company
Re-render the existing page. If no validation errors, the user would see the exact same page again, otherwise the same page with validation errors.
My main problem with achieving DRY has to do with all the controllers that invoke views that contain the partial view end up having to have an Action Method to process the form submission from the Quick Add. Even if I break out the logic for processing the information into a separate controller and invoke that method from each of the other controllers it seems like a burden that each and every controller that invoke views that have reusable controls have to have that knowledge.
The other option I looked at was to have the reusable control always submit to a specific action method / controller but then there is no way for that controller to know how to re-populate the model appropriately for the specific controller that invoked the view that contained the reusable control (in step 4).
I am aware that there is talk of subcontrollers in MVC 2 (from this question ASP.NET MVC - Contained User Controls) but since it is not there yet, what is the best way to structure the code to achieve maximum reusability while maintaining DRY?
Is there an alternative to having to have all the controllers that invoke views that use a reusable control (with the characteristics of the one described above), having to have an Action Method to process the information from the control?
At the end of your post, you ask "Is there an alternative to having to have all the controllers... having to have an Action Method to process the information from the control"
The answer for that question is to write a custom model binder. Your custom model binder can be responsible for the populating the values from the incoming form control(s) into model or properties used by all of the controllers. Normally, you want to separate the validation from the model binding, but there is no reason that you couldn't combine them as well.
I highly recommend 6 Tips for ASP.NET MVC Model Binding for a deeper discussion of the topic along with some good references.
I'm not sure why you say the Quick Add form has to have an action method in each controller that uses it; if you wrap the Quick add functionality in a Html.BeginForm(); Html.EndForm() combo, you can have the beginform method specify the name of the action and controller, so you only need one controller.
I understand where you are coming from; it's something I have been thinking about to. While I don't know all the answers, I have some ideas for you to consider. Every controller action method is invoked via a ControllerActionInvoker class, which you can customize. This class handles invoking all of the action methods, so here you could embed certain aspects of reusable code across all or certain action methods.
Look into filters too, as there are a variety of filters that you can use or customize that fire for action methods that implement it. This way, code can run before and after the action method execution and result execution.
For validation, there is already validation components built in that will prevent page submission... you could also consider XVAL which has some other nice features. The Unity framework is an IOC container framework, which dynamic injection keeps things loosely coupled and DRY, as you can inject all kinds of references.
Also, you mentioned subcontrollers; the MVC preview has additional features you may be interested in... for instance, it has a RenderAction method that can render an action method within another action's view.
Hopefully that helps... so what am I missing?
Have a look at RenderAction and RenderPartial. Those are the canonical ways to arbitrarily inject a common control into a view.
Use RenderPartial when you want to include the data as part of your ViewData infrastructure.
Use RenderAction when you want the data to be separate from the ViewData infrastructure. The data will come from the controller method you specify in RenderAction.
Check out the NerdDinner tutorials, if you haven't done so already.
Related
I've developed an ASP.NET user control, instances of which may appear several times on a single page. Without getting into too much application detail, when the value of any one of the instances changes, all of the other instances need to be refreshed. Currently, in order to accomplish this, I'm requiring that the consuming page implement a couple of methods which iterate through each control on the form, find all the instances of my user control, and call a Refresh method in each one.
Functionally, it's working perfectly. However, I'd like to force the developer of the consuming page to implement these two methods exactly as per my requirements. I could have them implement an interface, but that doesn't provide the functionality in each method. Or I could have them extend an abstract class, but in either case (interface or abstract class) how can I force them to inherit? I need something that will trigger a compiler error if the necessary abstract class is not extended by the consuming page. Any ideas?
Thanks.
You can enforce implementation by using 'abstract methods' in C# or using the 'MustInherit' keyword in VB.NET.
In your particular case, you're expecting the developer to essentially implement 'your' code to force the refreshing and this is something I wouldn't want delegate. Without knowing too many details I would be tempted to utilise the 'Observer' design pattern or possibly the 'Mediator' using either a separate object as a controller or even applying the controlling / publishing code to the webpage. Here's a practical example of the 'Observer' in ASP.NET.
HTH
I am trying to figure out where the appropriate place is to intercept the resolution of what view + controller is being called in ASP.Net MVC 2. I have a situation where I have a controller and a corresponding set of views. I also have the possibility of a customized version of both the controller and N of the views sitting in the project (or we may use something like Portable Views from the MvcContrib project). If the customized version of the controller or view(s) exists at run time, and the user satisfies certain criteria, I need to call the customized controller and use the appropriate customized view. At design/compile time we don't know what customizations may be in place.
My first run at this was by using a custom controller factory that returns a custom controller if it exists. However, this controller is "wired up" to the standard view, and I cannot figure out how to return the customized view if it also exists.
To complicate matters, there may be no customized controller but customized views, and visa-versa.
Sounds like you're on the right track. You've got custom controller selection logic in place, but you need to also have custom View selection logic.
You can override and extend the default ViewEngine to plug into your app that uses your own logic to look for the view locations. Here's a good walkthrough of a simple ViewEngine that does exactly that.
I'm fairly new to ASP.Net MVC 2 and understand the MVC pattern in itself. But my question is what's the best way to populate dropdownlists in the UI sticking to the MVC pattern. Should I be going through the controller?
Every article I've seen to do this shows how to do it using javascript and jquery. I have a test application that I'm re-writing in MVC2 I have my dropdowns working with jquery basically calling a WCF Data Service that returns JSON which populates the dropdowns. Seems to me though that this is bypassing the controller and going straight to the model therefore strictly violating the MVC pattern.
Or am I missing something obvious here. You thoughts or best practices would be greatly welcome here.
Thanks
One of the great things about MVC is that the controllers can couple as 'web services' or sort. Meaning, you can easily specify a return type of 'JsonResult' for example (instead of a view - ActionResult).
The MVC framework will handle all the serialization for you.
You can easily call the controller action method from jQuery and populate the dropdown.
In your example, i would create a Json controller method, decorate it with some custom action filters (check http headers that its a json http get request, etc), call it from jQuery and bind to your dropdown.
If your drop-down list is static (i.e. not a cascading drop-down list) then you can add an AvailableItems property to your model, set its value in your controller, and populate the list from that. If your list needs to be updated based on other user selections then you need to call back to an AJAX service of some type.
In general, if your application has script code that runs on the client, that code is going to be in your views. I personally don't see that as a violation of MVC.
I think your best bet is to give View Models a try.
You can build fill out data for special UI oriented models in the controller and pass that to the view. For drop downs, is there a reason you're loading through ajax? In most cases I've found you can just build a normal select list and sprinkle with javascript for dynamical functionality.
Your view model could have a IEnumerable<String> CityNames property that you then load into a dropdown in the view.
Is it my understanding that Helper methods are really the place where you can do the hard core logic that we would have done in lets say custom controls in ASP.NET? For instance I work for a .com which uses classic ASP.NET. The nature of our site is VERY complex, so we reuse and render different forms for thousands of products. Every product could have a different configuration form. We have a very complext RenderForm.cs custom server control that performs all the logic. Based on some configuration settings from a table in the DB, it says ok, for Product 1123 it reads the setup (that our users confugure form our internal admin system) and takes that and spits out the dynamic form (using literal controls and what not) to the p age.
So I'm thinking MVC now. Yea yea, it's all done in the View. Well partially. You're still going to have a need to have some custom logic in some .cs where it's not all embeded in your view. That would be foolish to think you're not going to have some class that will spit out some HTML..like some very hard core extensive helper methods.
So my question is, are helper methods or class where you now do your custom server control type of logic? it's basically kind of the same concept in that you need a place to put your "hard core" HTML rendering logic in some class other than a controller. Your controller is not responsible for rendering. So helper methods I guess are the so-called custom server controls in a way that I have in classic ASP.NET, figuratively speaking. I just need a yes or now on is the consensus that helper methods is the place to do all my hard core reusable logic that spits out html to the page and where I can embed custom controls into my view? Looks like it.
"Helpers are essentially static classes, designed to contain the UI logic that otherwise clutters up your UI. Think of these as UI utilities." link text
Yes, that is right on. If you do it right, you will start with the HTML helpers that MVC gives you, and you will gradually build up your own set of helpers that do even more and more for your specific project. You can get to the point where your view has only a few lines of code, which say something like, "Render entire view for Product 1123". The helpers will become your own "language" of renderers specific to your project, and you will be applying configuration, validation and everything else in a very DRY (Don-t Repeat Yourself) manner. It's phenomenal.
Update: Of course, only presentation stuff should go in your helpers. The goal is to stay DRY in your views. You still need to be careful to put into your ViewModels the things that belong in the ViewModels.
I would say "no"... or rather "only where you have to". More often than not, you can instead do the logic in the Controller (or a Service) and end up passing all the data required back to the View in ViewData. Somtimes this will mean multiple Views from one ControllerAction, less often it will mean logic in your View, and occasionally it means HtmlHelpers.
When you decide to use Helpers, it should be with the consideration that this means generated markup that won't be... well, in your markup. If you have (or later hire) a designer, that can be a problem. Or if you need to make a minor change to your layout, where do you go first? Your View or your Helpers?
[Edit] Also should ask yourself this: where is my code more easily unit tested? In a Service class which is just handing back View Data, or in a class that builds entire chunks of HTML and returns them as a String? If you're using TagBuilder, as you probably should be, then any change in the implementation of TagBuilder (even a change of whitespace handling) will break tests on a Helper without your code changing.
I'm not saying "don't use Helpers", I'm saying "don't abuse Helpers".
I am working on an ASP.NET MVC application that contains a header and menu on each page. The menu and header are dynamic. In other words, the menu items and header information are determined at runtime.
My initial thought is to build a base Controller from which all other controllers derive. In the base controller, I will obtain the menu and header data and insert the required information into the ViewData. Finally, I will use a ViewUserControl to display the header and menu through a master page template.
So, I'm trying to determine the best practice for building such functionality. Also, if this is the recommended approach, which method should I override (I'm guessing Execute) when obtaining the data for insertion into the ViewData.
I'm sure this is a common scenario, so any advice/best-practices would be appreciated! Thanks in advance!
EDIT:
I did find the following resources after posting this (of course), but any additional anecdotes would be awesome!
http://www.singingeels.com/Blogs/Nullable/2008/08/14/How_to_Handle_Side_Content_in_ASPNET_MVC.aspx
How do you use usercontrols in asp.net mvc that display an "island" of data?
Depends on where your information is coming from. We have standard view data that we use to generate some of the information we have on screen that we create in just this fashion. It works well and is easily maintained. We override the View method to implement strongly typed view names and use this information to retrieve some of the data that the master page requires as well.
You could write a helper extension to render the header/menu
That way you could have it show in different places in the view should you need to, but only one place for maintenance.
public static HtmlString MainMenu(this HtmlHelper helper)
Use a base controller class to implement generell filter methods. The controller class implements some filter interfaces IActionFilter, IAuthorizationFilter, IExceptionFilter and IResultFilter which are usefull to implement some common behavior for all controllers.
If the menu data is the same on all pages but different for each unique user.
Generate the menudata in an OnAuthorization or Initialize method of your controller base class. First will be called on authorization. Initialize will be called before every action method. You have access to ViewData Context. Generate the menudata there.
Put the view content for menu and header into the master page and access generated ViewData there.
I tackled a similar design challenge a couple months ago - implementing a breadcrumb feature that changes as user navigates from page to page.
I overrided the OnActionExecuting method to gather the breadcrumbs and store them in ViewData (I use the name of the action as the breadCrumb of the view). Then I updated the Master page to include a user control that takes the ViewData and renders the breadcrumbs.
One thing to be aware is that if you were using the default ASP.NET MVC error handling attribute [HandleError] and your error page is using the same Master page that attempts to read the ViewData, you will soon find out that you can't access ViewData from your error page and it will raise an exception. Depending on whether you need the ViewData for failure scenarios, the viable solution is to use a separate Master page or do this: How do I pass ViewData to a HandleError View?
I'll answer your question with another question. Will the base controller have to determine what type it really is in order to generate the proper menu data? If so, then you're defeating the purpose of polymorphism and the code to generate the data should go in each controller, perhaps in OnActionExecuting if the menu is the same for all actions. Pushing it back down into a parent class seems likely to end up with some switch statement in the parent class doing what each derived controller really ought to take care of.