Returning ad-hoc view models from ASP.NET MVC2 Controllers - asp.net-mvc

I'm porting an existing system to ASP.NET MVC2. In the current legacy app, the user can select from dozens of available fields to customize CRUD forms for different entities in the domain model, similar to the way ERP systems allow customization of core modules.
My question: I'm looking for a good pattern or example for this kind of behavior in ASP.NET MVC2. It seems to me it's rather like creating a ViewModel dynamically based upon user choices, or perhaps the right approach is data-driven view pages that aren't strongly-typed where I can reflect over the results client-side to determine field headings or something -- if that makes sense :). Or maybe I can drive AutoMapper or similar dynamically # runtime based on user choices?
The underlying domain model is EF4-based and I'm using a simple Repository pattern # present for the ViewModel.
TIA for any input! Michael

If I didn't find anything else that matched the needs and went on to do it custom, I would:
Use the ViewModel with all the fields / not just the ones the user picked.
Pass both the ViewModel and the view configuration to the view
Call some html helper that for each item in the configuration adds a field with the corresponding property in the model
The configuration could be passed as either part of a containing ViewModel or in a separate entry in ViewData
Depending on what you need, building/passing the view configuration could be put in an Action Filter. Alternatively the helper could pull it directly.
A different approach is if you need completely custom fields. I mean user defined fields. If that's the scenario, that's not typed at the controller level already, so I'd pass the list of fields/values to the view. The view can do a foreach on those adding the fields. Again that could be moved to a HtmlHelper.

Related

ASP.NET MVC List of Web Components in Model

I need to get dynamically a list of Web Controls from View to be used in the model(dropdownlists, inputs, checkboxes, ...). Is it possible? I generate the controls in Razor.
My application should store last values of all controls for each user into the database and use them as predefined values for the next call of the form.
Any advice would be appreciated.
I need to get dynamically a list of Web Controls from View to be used in the model
First of all, you're probably going to find MVC a lot easier to understand if you abandon terms like "web controls" and the like. Your view, which may not may not be utilizing helpers to do so, is simply building HTML. Nothing more.
But more to the point, what you're proposing is exactly the opposite of what MVC does. Your model should have no knowledge of the structure of the view. (inputs, selects, other form elements, etc.) The model contains the data and business logic necessary to render the view. The view then uses that data and logic to build its interface.
You can post the values from the resulting HTML form to a server-side action. Then from that action you can store those values in a database or do whatever you like with them. If the key/value pairs of those values can logically be structured into the form of a model then the action can accept that model as a parameter, if not then it can also just as easily accept parameters for each individual value. (Though if you find yourself using a lot of parameters it would be better to build a simple view model just to encapsulate them.)
The order of operations is something like:
A request is made to a controller action.
That controller action invokes logic on a model and provides that model to a view.
The view binds its UI elements to the model's data and renders the interface.
The user interacts with the interface and uses it to perform a request to another controller action.
That controller action receives the data from that request, performs server-side logic, etc.
and so on...

Creating a model for MVC

I'm building my first MVC project and I have a question about the model.
Each webpage can only contain 1 model, yet my page will require 2 models, one is the search option (the ability to narrow your search such as selecting price range, colour etc) as well as the data.
Is it really as simple as creating a new Model, similar to a ViewModel which in this case would only have 2 properties, a SearchModel and a ProductModel?
Yes, there are really two "models" which is sometimes confusing. There's the "View Model" and the "Domain Model." The view model is passed directly to and from the view. The domain model describes the real-life domain that you're dealing with and is what the database persists. Often, they are the same thing, such as if you're displaying information for a single real domain object (e.g., a car). If you have two domain models that go on one page, you should make a view model with both as properties.
If you are looking to have two models in a view then this question might provide useful information:
multiple-models-in-a-view
Edit:
A good example is the 'Manage' view in the default 'Account' controller of a fresh mvc app. It uses a partial view to handle the changing of a user's password. Whilst both views are using the same model type it shows how to implement a partial view. In this case both the main view and the partial are submitting to the same method on the controller, hence they need to use the same model (which is a parameter for the controller method). But if the partial were to invoke a different controller method then the submitted model could be different. Hope this makes sense :)

Editing only a partial model in ASP.Net MVC

I'm quite new to MVC, and stumbled on a problem. I've googled a lot but couldn't find a solution.
I'm using ASP.Net Membership with roles.
Lets say I have a model of a product with attributes:
Name
Art no
Category
How can I implement this so different roles cab only be allowed to edit parts of the object?
(Let's say one role cannot change the category of a product, for example.)
Is it possible to have different Views for the same Model or different Models for the same object?
If I leave out some of the properties, they will have NULL value when I save them.
I tried using #HTML.HiddenFor(...) but then the validation for those fields failed.
A ViewModel sounds like it would do the trick. For all but the most trivial of scenarios, you will get into problems when you tightly couple the Model and the View.
If you havent used them before, a ViewModel is simply a class (model) for the specific view you are rendering. You can customize required properties and validation on the ViewModel and then bind it to the Model, so the structure is most more flexible and easy to work with.
There is a detailed intro at ViewModels http://kazimanzurrashid.com/posts/asp-dot-net-mvc-viewmodel-usage-and-pick-your-best-pattern
EDIT
You could then have a ViewModel for each of the role, although if you are only looking to protect a property from being updated by certain roles there should be other solutions such as setting the html input to disabled and then testing on the server that the category value is still in its original state (note you should always perform such a test as the Post request can be altered).

ASP.NET MVC ViewModel to Hold Lists & "Images or YouTube URL's"

I'm posting this question because I do not know the best/correct way of doing the following.
My team-mate (the designer) sent me a good looking design that includes a wizard for adding new items (for auction). The user has to fill in all the required details which include the title, description, starting price...etc AND a list of tags (up to 4 tags - chosen from the database, will use auto complete) as well as a list of up to 3 images/youtube url's (for the sake of better explanation check this image out: http://i55.tinypic.com/2v11zzr.png)
Ok so I figured out how I should do the wizard ( reference: how to make a wizard with ASP.Net MVC) but I'm not sure about how to collect the lists and the images/url's. Here's what I'm thinking:
For the images/url's, I should create a parent view model from which two sub-classes (ImageViewModel & YoutubeUrlViewModel) would inherit from and then in the controller action when I parse the post data, I would check to see the instance of the parent view model and act accordingly.
Now about the lists, I'm not sure whether I should include a List in my view model or whether I should include 4 string properties representing the tags (the same will apply to the list of images/url's).
So what's the best way of doing this?
And Haacked to the rescue: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
:)

How Can I Hide Specific Elements on a Razor View Based on Security without Logic in View?

I have looked all over for elegant solutions to this not so age-old question. How can I lock down form elements within an ASP.Net MVC View, without adding if...then logic all over the place?
Ideally the BaseController, either from OnAuthorization, or OnResultExecultion, would check the rendering form elements and hide/not render them based on role and scope.
Another approach I have considered is writing some sort of custom attributes, so as to stay consistent with how how we lock down ActionResults with [Authorize]. Is this even possible without passing a list of hidden objects to the view and putting if's all over?
Other background info: We will have a database that will tell us at execution time (based on user role/scope) what elements will be hidden. We are using MVC3 with Razor Viewengine. We're utilizing a BaseController where any of the Controller methods can be overridden.
Any help on this would be deeply appreciated!
You could use a number of different methods:
Send the user to a different view (display only view) based on the action filter, or a condition in the controller.
On a field basis, you could build the logic into the editor templates to read custom data-annotations based on role/permission.
You can build HTML helpers to handle the logic and render the appropriate partial view, css class, or text.
For more reading:
How much logic is allowed in ASP.NET
MVC views?
ASP.NET MVC 2 Templates, Part 1: Introduction (there are 5 parts, very informative and a good place to start developing your own editor templates)

Resources