Data Annotations and MVC 4 - asp.net-mvc

I did MVC 2 two years ago. I am now using MVC 4 and would like to confirm a few things.
1) In MVC 4, we do not need to create a ModelMetadata class to annotate with data annotations for data validation. We may simply annotate the model classes themselves.
In other words, if we are using the EDM generator to generate a model and corresponding classes for us, then we may create a new set of partial classes with the same names and use data annotation attributes on those partial classes themselves.
We do not need to create a new type of model metadata class and decorate that class with data annotation/attributes, like here: http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validation-with-the-data-annotation-validators-cs
2) For data annotations to work, we need a reference only to System.ComponentModel.DataAnnotations and not to Microsoft.Web.Mvc.DataAnnotations.
3) We do not need to instantiate the default model binder in the Application_Start event in the Global.asax file.
Could you please confirm if my understanding is correct?

As I remember, there's no difference between MVC 2 and MVC 4 when it comes to this. You didn't have to use MetadataType in MVC 2, you could have used partial classes for generated models.
I'm not able to find any MSDN doc on Microsoft.Web.Mvc.DataAnnotations, but for data annotations to work with MVC you'd need System.ComponentModel.DataAnnotations and System.Web.Mvc (it contains some additional attributes like HiddenInputAttribute).
No, you don't, it's instantiated by framework.

Actually, for question 1, you need to use Metadata classes to annotate the properties of of model-first EF classes in the same way as previously with MVC2. When you use code-first EF classes, you can annotate them directly - the annotations will be used for generating the database as well as for scaffolding the Views.

Related

Should I use custom model binder to bind view model to entity?

Just some idea to make more use of custom model binder. I am currently still using IMapper interface to do so, though wondering whether part of the purpose of custom binder is to mapping view model or input model to business entity? I can see there might be some limitations if i use MVC custom binder. What is the advantage to use the custom binder in MVC? Will my app gain better performance?
Short answer would be No, you should not
ModelBinder by itself is part of ASP.NET MVC infrastructure. If you would take a look at ASP.NET MVC pipline (PDF) you would see that it's job is
to convert a posted web form data (a string basically) or query string from URL to an instance of particular class.
ASP.NET MVC framework has a DefaultModelBinder that
is suitable for 99% of cases. Custom model binders could be used in situations where standard data conversion fails e.g. mapping $ 1,234.56 from a textbox to a decimal value of 1234.56
Moreover ModelBinder implements IModelBinder interface with a single BindModel() method. This method expects parameters that would be hard to 'hand-craft' to make any use of them and are totally not relevant to your scenario.
What you are realy looking for is
- either custom object mapping between viewmodels and business objects where you manually assign one object property values to another
- or taking advantage of libs/frameworks such as Automapper or ValueInjecter which take care of object mapping hassle away from you
- or a mix of both

MVC ModelState and EntityFramework Validation

I have a edmx model done by Database First and generating the DBSet with the VS tools. I extended with partials the classes to add dataannotation validation to it.
I am receiving on my controller the view model which I am manually controlling the validation of fields. So eventhough I have a required field on my partial class, I am removing it once in my controller ModelState.Remove("pasajeros[" + count + "].numResidencia"); because of some conditions.
Before, I was using LINQTOSQL and I had no problems. But now Entity framework is not honoring my customization of ModelState.
How do i propagate or GO about this issue with EntityFramework?
thanks
Keep your view models and Entity models separate. Put your validation annotations on your view models. Then use a tool like Automapper to map the Entity to ViewModel fields for you.
On edit you validate your view model then update your Entity fields which you then save.

Model layer dependency on MVC attributes

We have an MVC3 project that uses nHibernate; there is a separate model project that contains all the model classes which is used by the repository and service layers. The models make use of data annotations like DisplayAttribute and RequiredAttribute from System.ComponentModel.DataAnnotations.
There are also attributes such as RemoteAttribute that are contained in System.Web.Mvc.
This of course means that the model project now has a dependency to a particular front end technology.
Assuming the solution could have other front ends what would be the best way to handle this dependency link?
RemoteAttribute does not belong in the model, since it specifies a controller/action to validate the property on the server, and the model shouldn't have knowledge of concepts like controller, action or route. The presentation layer depends on the model, not the other way around.
I would create a view model that inherits the model, overrides the property (must be virtual) and adds the RemoteAttribute. This way you can avoid duplication and mapping, although that's also an alternative.
To reduce dependency between database model and frontend technology, you can use special view model for validation qnd other front end actions in controller and put data from viewmodel to database entity after it.

ASP.NET MVC to call my Dependency Resolver when creating an instance?

I'm very new to ASP.NET MVC so I hope my question makes sense. I'm using POCO objects as my model. It's my understanding that when the form is submitted MVC can create a new instance of my business object and fill the properties from the form automatically.
I use dependency injection so I create new instances using code like the following:
DependencyResolver.Current.CreateInstance(Of IBusObject)
How can I get ASP.NET MVC to call this method instead of trying to create a new instance by using the "new" keyword on the concrete class?
Looking at the MVC source code it will not use dependency resolution when creating an instance of the model type, so you can't get what you want out of the box, but you could easily achieve what you want by creating your own model binder which is DependencyResolver aware.
You could write a custom model binder deriving from the default model binder and override the CreateModel method to supply your custom instance.

Choose the best Client/Server Validation Framework for MVC

Im trying to choose the best server/client validation framework to use with my MVC application. I would like to know what is the best validation framework to use with MVC to do server/client validation.
My options are:
Castle validator
Microsoft Data Annotations
nHibernate Validator
With the upcoming MVC 2, it looks like MS is leaning towards the System.ComponentModel.DataAnnotations library. It's pretty nice - does a lot of code generation for you.
I've been using xVal with great success.
The best thing is you can fully automate validation:
put DataAnnotations (or special rules) to your business layer POCO classes (if you have them) or entity classes' metadata buddy classes if you use entities up to controller layer
write an ActionFilter that will automatically validate parameters to your controller actions - it's best if all your POCOs (or entities) implement a certain interface that defines Validate() method, filter calls this method and fills ModelState.Errors when validation fails.
Add if (ModelState.IsValid) { ... } in your controller action that needs to work differently when model isn't valid
Put <%= Html.ValidationMessage(...) %> in your views that will display validation errors
Add xVal's client validation to your views if desired
This way you've set up automatic object validation. All your controller actions will do is check Model validity.
Asp.net MVC 2 will have something very similar to xVal already built in the framework so it's up to you which version are you using.

Resources