How to make rich/compound views - asp.net

I have recently started to examine ASP.NET MVC. I have studied quite a few examples and common to these are that they contain quite simple scenarios, where a view will map to either an instance of a type in the model or a list of a paritcular type from the model.
I'm looking for guidelines to compose/composite views. In the long term I would like Ajax to be part of the equation, but for now I'm looking for a simpler non Ajax setup.
The problem
Here is a description of a contrieved problem. A domain model contains the types A and B.
class A
{ String ID, String Name, int Age
List<B> ListOfB
}
class B
{ String ID, String Name, String Url}
I would like to have a that allows the following:
A DropDownList showing type A information
Details about the particular A picked in the dropdown
A list showing type B's related to the selected type A
A form that makes it possible to edit the data of a selected type A
A form that enables the user to add a new B.
The view should not show all of this at once, instead it has to show different combinations of information and functionality according to user input. Combinations of detail and functionality could forexample be:
Initially only show the dropdownlist containing A's
If an A has been selected in the dropdown:
Show the particular A as selected in the dropdown
Show detail info about the selected A
Show list of detail info of related type B's
The user wants to edit a particular A
Show the particular A as selected in the dropdown
Show form that allows user to edit particular A
Show list of detail info of related type B's
The user wants to add a new B
Show the particular A as selected in the dropdown
Show detail info about the selected A
Show list of detail info of related type B's
That could look something like this (used the web version of balsamiq mockups - what a fantastic invention!):
Combination 2:
Combination 4:
Creating the view and controller
Since the solution has to allow for different combinations of data and functionality, I think it would be smart to have a parent view (not to be confused with a masterpage) that contained placeholders for parital views. Then, the parent views controller could make up the right combinations of model data and partial views and feed these to the parent view.
Finally; the questions:
Is my way of thinking in accordance with the asp.net mvc methodology?
Can you explain/show (not necessarily all of it) how the controller can compile the right combination of partial views and feed these to the parent view?
Can you point me towards an Ajax based solution?
Can you suggest books/links that contain examples of complex views?

asp.net mvc fully supports all of your requirements but there are few things you should get up to speed on:
You should look at implementing view models to help seperate your domain model from your specific views. Here is a good link on how to start this.
You need to get up to speed with a client side javascript framework for the ajax work with partial html rendering. jquery will do this or ms ajax. Here is an example
To your detailed questions:
Is my way of thinking in accordance with the asp.net mvc methodology?
Asp.net mvc is not going to constrain you at all so essentially this is fully supported
Can you explain/show (not necessarily all of it) how the controller can compile the right combination of partial views and feed these to the parent view?
You can use partial views if you want to seperate bits of code out and can easily refresh them by loading them independently using ms ajax or jquery. You would have a controller that mapped onto your parent view and can delegate and refresh partial views in ajax calls.
Can you point me towards an Ajax based solution?
jquery will do this or ms ajax. Here is an example
Can you suggest books/links that contain examples of complex views?
This link talks a lot about this.

Related

Asp.net setting some context for a Custom UITypeEditor from parent form at Design Time

Trying to craft a way for our designers to create custom asp.net webforms for our customers. The basic idea is that we have a general set of fields that can be saved, with each customer using a subset of those fields, each customer may have it's own names for similar concepts (ie one customer may use 'patient' and another 'customer'). Staying in customer context will help the designers build the correct form to meet the customers needs.
Now to do this I need to get as much as I can into the design experience as possible. I have a set of custom controls that derive from base controls like asp:TextBox and implements an interface to allows me to iterate over the controls and insert values from a data store, or fetch values to persist (Done). All of these controls need to be bound to a data point in my record object. I have a metadata system set up to allow the binding, but where I am running into trouble is in getting the list of available fields into a UITypeEditor. Namely, I haven't figured out how to (at design time) set the customer context on the form, and then access and use that value on each controls custom property editor (also at design time). Is this possible? Am I looking at this problem the wrong way? A form always has 1 and only one customer context. So in my forms project, each form will have a different customer id set to it.
As a second question how can I debug these editors? There is an expectation of web context in the editors, but there is no asp.net property grid. and even if there was, the editors are winforms components that wouldn't run in a browser.
I can include the code I currently have if it simplifies the problem, but even a simplified example is a half dozen classes.
I resolved these issues, posting here in case a general solution can be useful to anyone in the future.
I was able to get around this problem a bit by going the other way. My parent Page iterates over it's controls, and sets the CustomerId on all the controls that implement a specific interface.
As for debugging. Some refactoring got me to a place where I can easily swap out the webforms specific parts of my implementation for testing.

ASP.NET MVC: Basic form question

A friend has asked me to help him with a project that's MVC. This is my first experience with MVC. I'm trying to build the MVC components for a form for him.
A page has a modal popup which uses a JavaScript to POST or GET and receive HTML backā€”that it displays inside the popup modal.
I need to create an MVC form that has validation to display inside aforementioned popup. This popped-up form will be used elsewhere on the site, so needs to be modular.
Should I create an ActionResult in my Route's Controller that returns an View (.aspx) containing my form? Should I instead create a Partial View (.ascx) that has the form, then use that Partial View in a View for my Route so other parts of the site--other Routes--can do the same?
I'm stuck at that basic understanding. From there, I don't even know what to do about the validation (was told the same validation will be used on a nearly identical form) and how a ViewModel fits into this like is used elsewhere on the site.
I've been reading a lot and looking at a lot of examples but I'm still confused.
You've got two separate questions here really. To deal with whether you should use a partial view or a regular view, just think of it this way. Does the HTML content in question represent a full page, or just a piece of a page that will be reused inside of other pages?
If it's the former, then use a full View. If it's the latter, then put it in a partial view. It sounds to me like you just need a full View. In either case, it's easy to change to the other if it turns out it's not meeting your needs.
As to validation, take a look at xVal if you're using ASP.Net MVC 1. It allows for easy validation using attributes on your models.
When you make your post from the modal popup do the validation then in the actionmethod you created specifically for that popup. If you want client side validation write up the js to do it.
As for the modal markup and what not just create a partial view for that, shouldn't be a big deal.

ASP.NET MVC - How to achieve reusable user controls and maintain DRY?

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.

How to make a general form in Flex to deal with Entity CRUD?

I would like to create a general form so that it can deal with creation/read/update of an entity. When creating an entity, it may only contain a subset of all fields; when updating the entity, it may contain a different subset of fields; and when reading the entity, none of the fields are editable. Anyone with experience in designing such a form in Flex? Thanks in advance.
I was frustrated with the quality of the flex forms as well, especially managing the validation, so I wrote my own form control. It's a bit haphazard and buggy at times so it's not ready for sharing, but I'll cover the ideas:
Separated into a layout part and a data part, matched by keys. Both are basically combinations of AS3 Objects/Arrays containing the properties I need.
Describe all the possible visible elements in the layout, the validators needed, visual properties, labels ,etc... Every element in the layout is an Object in an Array. The primary array is ordered and displayed via a VBox. Any nested arrays are displayed in a nested HBox (e.g., useful for radio options).
The data part of the form is where you can set initial values, "editable" properties, "model" properties (for combo boxes), things like that. The data structure is an Object hash where the keys map to elements in the layout. If an entry from the layout does not exist in the data definition, it does not appear. This allows you to easily hide sections you don't want to show.
Has an errors sections where validation or server errors can be displayed.
Has a collect function that collects all the data into an object hash.
Has a validate function to control when the validators are triggered.
Non editable fields show up as labels.
Basically I've implemented my own "Form" control, and each entry in the layout (when displayed) becomes a custom "FormItem" control that will be whatever type the layout described. ("text","combo","heading",...)
Hard to describe without visual examples and some code, but that's the basic idea. You're on the right track thinking that you need your own control. There's too much hand-holding required for the generic forms, and lots of redundant code.
Check out Rocket Framework .. you gonna love it..
Want to automate winforms? not just CRUD, this help creating any type of winforms controls. The Rocket Framework for WinForm (using .net c# 4 ) provides a set of easily utilizable generic library to seemlessly develop 'form based' application/ control / custom controls for .Net.

Using a Base Controller for obtaining Common ViewData

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.

Resources