Shayan
Shayan

Reputation: 402

Validation in ASP.MVC 3.0

I have a model class :

public class YearlyChageRate
{
    public int Year { get; set; }
    public double Rate { get; set; }
}

and I want to check that Yeae is unique or no and in condition Year is not unique application show an error message to users.How can I check the Year filed is repeated or not?

Upvotes: 0

Views: 112

Answers (3)

Matteo Mosca
Matteo Mosca

Reputation: 7448

Although you can use DataAnnotations attributes for validation and the [Remote] attribute for checks against the DB, it's not a very good design choice.

Let me explain:

  • data access is a data-layer matter
  • validation is a business-layer matter
  • user input and feedback is a ui matter

With DataAnnotations, you're mixin 3 in 1. It can be faster, but surely not well designed.

You could try a more disciplinate approach, like this:

  • Have a method at business level that will take your object as a parameter, perform validation internally using a validation framework of your choiche;
  • This method will call the data access to persist the object only if the validation passed;
  • This method will always return to the UI the validated object, plus a collection of fields/errors if anything didn't validate;
  • When you read the output of the method in your ui, you can either display a success page if there were no errors, or redisplay the form with the validation errors returned. To do this, the use of the PRG pattern is highly recommended, as you should never display a page on a POST method. Google for the PRG pattern to learn more about it. MvcContrib has a nice ActionFilter called ModelStateToTempData to make the implementation of the PRG pattern something trivial.

Upvotes: 1

Evgeniy Labunskiy
Evgeniy Labunskiy

Reputation: 2042

Here is a good example: http://tugberkugurlu.com/archive/asp-net-mvc-remote-validation-for-multiple-fields-with-additionalfields-property

And here too: MVC validation for unique

You can use Remote attribute in your model to perform check for unique value in database.

This is official example of Remote attribute: http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

And one more: http://www.a2zdotnet.com/View.aspx?Id=198

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039368

You could use the [Remote] validation attribute on your view model.

Upvotes: 1

Related Questions