Should I render optional sections of a form via partials? - asp.net-mvc

As an exercise in learning .NET, I'm moving some simple forms over into MVC, and have run into an issue. The form in question is a multi-part form that has option sections. For example, Section 0 is static and contains information like username, real name, email address. After that is a radio button with several options. If you click the first radio, it displays Section 1. If you choose the second, it displays Section 2, and so on.
In WebForms this was no biggy, as I just validated on postback and said if Radio1.Selected validate this, if Radio2.Selected validate that, etc. So now I've got a strongly-typed view with [Required] members, which obviously isn't going to work - I can't require members that aren't always going to be required.
With that said, is this the correct approach to the problem:
Create the members that belong in Section 0 in my strongly-typed view model class.
Create references to each partial's strongly-typed class in my view model class.
Create the partial views and then render them in the main view.
Depending on which radio button is selected, render the appropriate partial view.
Validate the model like usual...which hopefully will cascade to the partial models.
Does this make sense, or is the approach wrong?

That's a typical scenario where you need conditional validation, i.e. if some value is set then validate that some other value is required. Achieving this with static data annotations which are simple attributes baked at compile time can quickly turn into a nightmare due to their declarative nature. Well, you could always roll your own custom validation attributes but the problem with attributes is that you will have to specify property names as strings as they need to be known at compile time.
That's one of the reasons why I use FluentValidation.NET. Not only that validation rules are separate from the view models and that it integrates really nicely with ASP.NET MVC but handling scenarios like this would be very easy. You could have a sub-view model containing all the properties of the sub-section and then conditionally include it based on the value of a given property on the main view model inside its validator.

Related

Is creating ViewModel for Model validation odd and unnecessary?

Is there any good reasons to create ViewModel that copy`s Model with addition of validation logic?
Why not simply extend current model with validation logic?
If you will create ViewModel copy, you need to
Create class with corresponding fields (which is not big problem if you have few models to validate, but what if you have many..)
Set automapper, wich can be slow, and adds additional logic to your solution (or do it by hand, which is probably, bad idea)
Support Model changes for ViewModel
These problems dissapear if you simply extend your basic Model. So why it is so popular to create ViewModel layer?
You can have two views with different validation logic for the same model.
the classic example is a sign up form, with a single page form vs a multi page wizard.
In both cases the model is the same, but in the wizard view its legitimate to submit the model half filled in, while the single page version should have all the fields validated.
Taking this possibility further leads to the one viewmodel per view methodology. Where you always make a viewmodel for a view as a matter of course because you expect to need the flexibility that it offers as a general thing.
Additionally, its pretty rare that view exactly matches a model. You usually require more than one model plus some odd extra bits. eg user model for the 'logged in as' header, list of models to display plus pagination info.
You can avoid some of the issues you mention by using ViewModels which simply wrap models and expose their properties where extra logic isn't required

Razor view display domain model properties without knowing the domain model

Background: I have a simple mapping app (backed by GeoServer) that allow a user to click on a feature and select a data table displaying information about the selected feature. A HTML table would then be inserted under the map to show the query results.
Problem: Since there are at least 40 something tables that the user can select, I don't want to build 40+ partial views. Is it possible to build a Razor view that can handle any model passed to it and build a HTML table without knowing the domain model's structure? I'm leaning toward no after some poking around.
Reference: Related to my previous question of
Dynamic DBSet lookup and query
Practically, asp.net mvc already does that when you call EditorForModel, DisplayForModel or similar. If there is no developer defined view for corresponding model type, it calls object template, which uses reflection to render editor and display views. That template does not have predefined knowledge of model type.
You could set model type to object for view, and make use of reflection to generate tables.

Scope of viewmodels in asp.net MVC 3

I have read online that it is bad practice to use a "kitchen sink" model:
Rule #3 – The View dictates the design of the ViewModel. Only what is
required to render a View is passed in with the ViewModel.
If a Customer object has fifty properties, but one component only
shows their name, then we create a custom ViewModel type with only
those two properties.
Jimmy Bogard's subsequent explanation of how this is good, however, left me a little questioning. It'd be so easy to have my Model just contain a list of Customers, I could even use my POCO's.
So now I get to create custom little view model fragments for every page on the site? Every page that uses a Customer property would get one, but of course could not be shared since some of the information is extraneous, if one page used Age but not Name, for example. Two new mini view model classes right?
This is very time consuming, and seems like it'll lead to a million little custom view models - can someone elaborate as to the utility of this approach and why the easier approach is bad?
View model class can be used not only to transfer values, but it also defines data types (data annotations), validation rules and relations different then ones used in model. Some advantages that come to my mind right now:
There are different validation rules when you change user's password,
change his basic data or his subscription setting. It can be
complicated to define all these rules in one model class. It looks
much better and cleaner when different view models are used.
Using view model can also give you performance advantages. If you
want to display user list, you can define view model with id and name
only and use index to retrieve it from database. If you retrieved
whole objects and pass it to view, you transfer more data from
database than you need to.
You can define display, and editor templates for view models and reuse them on different pages using html helpers. It looks much worse, when you define templates for model POCOs.
If you would use your POCO objects as view models, you would essentially be showing your private objects and break the encapsulation. This in turn would make your model hard to change without altering the corresponding views.
Your data objects may contain details that are appropriate only to the data access layer. If you expose those things to the view, someone might alter those values that you did not expect to be altered and cause bugs.
Many of the same reasons as for having private members in OO languages apply to this reasoning. That being said, it's still very often broken because it's a lot of extra work to create all these "throw-away" models that only gets used once. There exists frameworks for creating these sorts of models, though the name eludes me, that can tie objects together and pick out the interesting properties only which takes away some of the drudgery from creating specific view models.
Your View Model tells the View how data should be shown. It expresses the model. I don't think its necessary to have two view models unless you have two ways to express your model. Just because you have two pages, doesn't mean you will be showing the data any different way, so I wouldn't waste time making two mini View Models when it can be in one reusable view model, Imagine if later you have a page that needs Name and Age, you would create another view model? It's absolutely silly. However, if you had two pages both showing 'Age' and it needed to be shown in a different way, then I would create another one.

ASP.NET MVC 2 Custom Model Binding Question

Background
I have a payment page where the user can select from a list of existing payment methods, or specify a new one. The dropdown presents options such as:
Visa - ******1234 (Saved)
Mastercard - ******9876 (Saved)
[New Credit Card ...]
[New Electronic Check ...]
Using jQuery, I toggle hidden DIVs that contain either an informational table (in the case of options 1 or 2 for saved payment methods) or a form (in the case of the [new] options).
I am using a strongly typed class as my view model which contains (among simple types) a CreditCard class and a Check class. Each of these classes uses data annotation validators, as they are used in other parts of the site.
Problem
The problem comes in when the user submits the form. I would like to use model binding to handle the mapping of POST values, but I need the binding and/or validation to fire depending on which option the user selected. For example, if the user selects option 1 or 2 from the list above, I don't want the model validation (or maybe even the binding itself) to fire for the CreditCard or Check objects.
I have researched the possibilities of creating a custom model binder using IModelBinder as well as extending the DefaultModelBinder and just overriding some of the methods. However, I am unsure as to which method is better, and, if extending DefaultModelBinder, which would be the appropriate method to override.
The logic would be fairly simple:
If the user selected one of the existing payment methods, no validation on the CreditCard or Check are required.
If the user selected one of the options to create a new payment method, then only the selected method (CreditCard or Check) needs to be bound and validated
It feels as if extending the DefaultModelBinder is the way to go, as I would like most of the heavy lifting to be done by the framework without the need to create a custom binder from scratch. However, when looking at the available methods to override, it's not clear which is the best one(s):
BindProperty - The problem here is that I basically need to look at one of the properties to determine what other properties should be bound. I don't think I can control the order in which the incoming properties are bound, and I wouldn't want to rely on the order they are set in the HTML form.
OnModelUpdated - By this point, it's too late. The binding validation from the data annotations has been triggered and the ModelState has been updated. I would have to loop through the ModelState and remove the errors that are not relevant.
OnPropertyValidating - At first I thought this is where I should look, but even returning TRUE for all properties (as a test) causes the ModelState to contain binding errors.
I have come across this scenario in other aspects of the application and decided to split up functionality into separate controller/actions to simplify the process. However, I would like to have a better understanding of how to approach more complex UI problems, particularly related to the MVC model binding features.
Any help on this subject would be greatly appreciated.
All the possible values are stored in a dropdown list. Using jQuery, I toggle the form (for a new payment method) and the display (for an existing method)
I have decided to try to circumvent model binding altogether and use FormCollection, IValueProvider, and TryUpdateModel inside my controller action.
Your issue sounds way to specialized to be placed in the default ModelBinder.
The ModelBinder is this seductress that lures you in on the pretense that she can solve all of your problems. But then you start merging ModelState's together and going off to do crazy things with nested objects lists and before you know it she slaps you with divorce papers and takes everything but your bones.
MVC 3 holds some promise to provide a more extensible ModelBinder but from my own personal experience unless its super simple what you need to change, such as empty texboxes becoming "" instead of null, than stay clear away from your own implementation.
The alternative approach is to use the existing ModelBinder functionality piecemeal and using things like Ignore method parameters to clean things up:
if( myModel.IsNewPayment )
UpdateModel( myModel.Payment, "exclude everything else" );
A lot of what your proposing to stuff into the model binder is really business logic too that should be in another layer. I've done some crazy things with my own ModelBinder and now regret every line of code I've written in there. Maybe its just me but your really bending the rules and completely trashing the "single responsibility principal" by putting business and payment logic in there.

MVC reusable propertygrid

In my web application framework (currently WebForms) I have a control that behaves like a classic propertygrid. It is initialized with an object ID (database key), then it reads metadata to determine the type of the object and the attributes of the object. It displays the attributes, string attributes as textboxes, bool attributes as checkboxes, enum attributes as dropdown lists. On page submit there is a method of the control ctrl.SaveData() that saved the changed attribute values back to the database.
The WebForm control tree and event model supports this approach quite nicely. Now I am asking myself if it is possible to achieve a similar solution for ASP.NET MVC. The main objective is to have a generic, reusable component that can be applied in a variety of situations with not much hassle. Additionally the solution must be flexible enough to put multiple instances of the component for multiple objects on a single page. Here the auto-generated WebForms HTML IDs also helped.
I am very curious about your ideas! Thanks a lot for answering!
You could achieve this effect using a custom ViewModel that contains enough metadata to identify the object being edited/saved. You would use this in conjunction with a partial view that renders the ViewModel. The main page would use the metadata in the ViewModel to either direct the post to a specific controller action to save that particular object or pass the metadata back to a common action (as hidden inputs, perhaps) in order that that action can choose the proper table in which to persist the data.
Personally, I would not take this approach. My feeling is that the more general you make a view/action, the more work it becomes to adapt it for different circumstances. I have done similar things for viewing sets of objects, but for a detail view or editing I like to work with more specific models and views.

Resources