- Published on
Typical data annotations to use in an MVC data model
- Authors
- Name
- Mike Barram
In ASP.Net MVC, the data model can use data annotations to describe how a property should be displayed or validated.
[DisplayName("Label used for field goes here")]
If a string field in the database (e.g. varchar()) doesn’t allow nulls you should either have[Required(ErrorMessage = "Required")]
to provide a message when a field hasn’t been entered
or
[DisplayFormat(ConvertEmptyStringToNull = false)]
if empty strings are allowed (though you might want to allow nulls if that’s the case)
[StringLength(255, ErrorMessage = "Maximum chars 255")]
[Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.MultilineText)]
– the editor will be a textarea
If your text includes HTML then you’ll need[AllowHtml]
And you might want to use a custom WYSIWYG editor[UIHint("WYSIWYG_basic")]
There are lots of other data annotations for different data types such as EmailAddress or ImageUrl:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.datatype(v=vs.110).aspx
You may want to add UI Hints for some of these data types, so that for an image, say, you use a template that displays the image when viewing but lets you upload/replace the image when editing:
https://digitaltoolfactory.net/blog/2012/04/how-to-use-ui-hints-and-display-templates-in-asp-net-mvc-3/
More on data annotations:
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-6