为什么ASP.Net MVC范围属性采取类型? [英] why does ASP.Net MVC Range Attribute take a Type?

查看:140
本文介绍了为什么ASP.Net MVC范围属性采取类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,为什么范围验证属性可以接受一个类型和两个字符串作为参数?这是用于验证字符串对一个​​枚举或这样的事情?

I was just wondering why the Range validation attribute can take a Type and two strings as parameters? Is this for validating strings against an Enum or something like this?

还有什么,我试图做的是找到一种简单的方法来验证它必须是一个枚举present 3字符串,任何建议吗?

Also what I am trying to do is find an easy way to validate a 3 character string which must be present in an enum, any sugestions?

谢谢,
亚历克斯。

Thanks, Alex.

推荐答案

我没有找到你所提到的腥范围构造函数。不由得调查。 (所以我写了这个答案就像一个日志,而调查)。

I did find the Range ctor you mentioned fishy. Couldn't help but investigate. (So I wrote this answer like a log while investigating.)

public RangeAttribute(
    Type type,
    string minimum,
    string maximum
)

请注意:MSDN说键入 IComparable的。而且,他们的例子描述说,它的日期比较时,它不是!

Note : MSDN says the Type should be IComparable. And, their example description says its for a date comparison when its not!.

所以,因为我有我的生产asp.net MVC3应用程序打开我的日期时间这样的尝试这样一个:

So since I had my production asp.net mvc3 app opened I tried this on a with a date time like this:

[Range(typeof(DateTime),"1-Jan-1910","1-Jan-2060")]

当我运行它发生这种情况:

When I run it this happens:

请注意如何我虽然规定的最小和最大用虚线,没有时间,它给不同的格式,所以它可能是 TryParsing 字符串吧?但我敢肯定这不可能 ICompare 这两个客户端上的!?现在,无论输入怎样的日期仍显示错误。 (日期是在2020年输入为11-MAR-20(20时)。)

Note how although I specified the minimum and maximum with dashed and no time, it gives a different format, so its probably TryParsing the strings right? But I'm sure it can't possibly ICompare the two on the client side!? Now no matter what date I enter still shows the error. (The Date is entered as 11-Mar-20 (20 as in 2020).)

我试过CHAR(如下图),这就是因为一个 IComparable的太。一样。它不能真正能做到的客户端的一个范围比较。

I tried char (below), since thats an IComparable too. Same thing. It can't actually manage to do a range comparison on the client side.

[Range(typeof(char), "a", "g")]

别急...

只是删除​​客户端验证!我删除引用jQuery验证和不引人注目的验证和中提琴!它完美的作品。它的帖子显示了错误的正确当值(CHAR和日期)不在指定的范围内。

But wait...

Just remove Client Validation! I Removed References to JQuery validation and Unobtrusive validation and viola! It works perfect. It posts, then shows the errors correctly when the values (Both Char and Date) are NOT within the specified range.

注意:也许有人可以扩展此解决方案仅禁用某些领域的客户端验证

Note: Maybe someone can expand this solution to disabling ONLY certain fields for client validation.

希望这是有益的。

这篇关于为什么ASP.Net MVC范围属性采取类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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