简体   繁体   中英

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?

您可以在视图模型上使用[Remote]验证属性。

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM