在MVC中应用多个数据注释 [英] Apply Multiple Data Annotation in MVC

查看:58
本文介绍了在MVC中应用多个数据注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在名为Year的属性上应用多个数据注释。



以下是我的代码:

I want to apply multiple data annotation on a property named Year.

Following is my code:

[Required(Error Message="Year is Required")]
[Range(1900, 2050, ErrorMessage = "Enter the Valid Year")]
public string Year





当我输入无效年份时,它工作正常,但是当我没有进入任何一年文本框,它再次显示范围错误,但预期的错误消息是:年份是必需的。



请帮助..



When i enter an invalid year then it is working fine but when i do not enter any year in the textbox , it is again showing the Range error but the expected error message is :"Year is Required".

Please Help..

推荐答案

从您发布的几个代码中,很难确切地知道错误的来源。我可以看到你的Year是一个String,所以你可能在输入时将它转换为int,所以你可以用你的范围进行验证。



一些可能性我可以想象:

- 如果字符串为空,转换为数字可能会返回一个错误代码,无论如何评估它都超出了你的范围

- 变量你用来保持转换后的year已经有一个值(可能是0),当字符串的转换不成功时,变量保持初始值,并且该值超出你的范围触发错误的错误信息。



由于您没有提供有关代码的更多信息,因此很难知道错误的位置。



请查看 http:// msdn。 microsoft.com/en-us/library/vstudio/sf1aw27b(v=vs.110).aspx [ ^ ]。它可能会给你一个可能的方法(至少)有一个更好的错误处理
From the few code you have posted, it is difficult to know exactly where the error comes. As I can see your "Year" is a String, so you are probably converting it to int when entered, so you can validate with your range.

Some possiblities that I can imagine:
- If the string is empty, the conversion to number might return a error code that you anyways evaluate and it is out of your range
- The variable you are using to hold the converted "year" is already having a value (probably 0), when the conversion of the string is not successful, the variable remains with initialized value, and that value is out of your range triggering the wrong error message.

Since you are not giving more information about your code, it is difficult to know where the error is.

Please have a look to http://msdn.microsoft.com/en-us/library/vstudio/sf1aw27b(v=vs.110).aspx[^]. It might give you a possible approach to (at least) have a better error handling


这篇关于在MVC中应用多个数据注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆