I’m using ASP.NET MVC 3 for a project I have.
The problem is that I would like to save a value to the database, which should before saving into the database be “cleaned” (say removing trailing and ending spaces, and also validate).
I use a MetaData Class to validate the models before I save it to the database with data annotations, using the following code to validate:
if (ModelState.IsValid) {
My MetaData Class looks like this:
public class OrganizationMD {
[Required(ErrorMessage = "*This field is required.")]
[CustomValidationRule(ErrorMessage = "*Another error message")]
public string OrganizationNumber;
}
My first idea was to give the OrganizationNumber string a getter and setter, and there let the value become “fixed”.
For example if someone tries to save a company with “19860415-4785” as organizationnumber, it should automatically remove the trailing “19” and the dash in the string before validating and saving that new value into the database.
I can’t give the model a getter and setter because we’re developing using Model-First, otherwise I think that should work.
Does anyone have any idea how to solve this?
You could create a view model to pass the the data to/from the view and controller instead of using your domain (entity framework) model directly.
Put your data annotations on the view model’s property.
Then you can do whatever you think will work in the getter and setter before mapping back to the domain model for persisting.
For readability and easier debugging, you could do your ‘cleaning’ in the controller instead of in the getter and setter, but that’s up to you.