Form validation in MVC 3 without attribution
I have multiple开发者_如何学Python MVC 3 forms that need form validation on certain fields (mostly to test empty submission). Some of my view models come directly from an ORM classes, so I don't have access to attribute required fields. Do I need to create additional classes (i.e., make a mega-ViewModel above the ORM class) to populate so I can attribute these or do other options exist (such as jQuery)?
Some of my view models come directly from an ORM classes
So those are not real view models but models. I would recommend you defining specific view models for each view/form. The view model should contain only the properties used by the view and be decorated with the necessary validation attributes for this particular view. This way you can handle validation as you like. So my advice is to always create and use view models which are specifically tailored to the requirements of a given view and map them to and from the domain models.
You may take a look at the following answer for some ideas.
Viewmodels are the recommendation - however many projects choose not to use them as their basic functionality for some reason - maybe simplicity.
So to answer the question specifically though - you can define metadata classes that then contain the same properties as your existing classes. Best practice is to use view models - but you can indeed do this with your existing models Something like this
//Defines that you are going to use CustomerMetaData as the class to define the rules. //This is named the same as your ORM class and doesnt need to contain anything in it. [MetadataType(typeof(CustomerMetaData))] public partial class Customer { //Don't need anything here } public class CustomerMetaData { [Required()] public string CustomerName {get;set;} }
精彩评论