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:
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:
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.