ASP.NET MVC 默认绑定器:整数太长,验证错误消息为空
我有以下模型类(为简单起见,已删除):
public class Info
{
public int IntData { get; set; }
}
这是使用此模型的 Razor 表单:
@model Info
@Html.ValidationSummary()
@using (Html.BeginForm())
{
@Html.TextBoxFor(x => x.IntData)
<input type="submit" />
}
现在,如果我在文本框中输入非数字数据,我会收到正确的验证消息,即:“Value 'qqqqq'对于字段“IntData”无效”。
但是,如果我输入很长的数字序列(例如 345234775637544),我会收到一个空的验证摘要。
在我的控制器代码中,我看到 ModelState.IsValid
为 false
正如预期的那样,而 ModelState["IntData"].Errors[0]
为如下所示:
{System.Web.Mvc.ModelError}
ErrorMessage: ""
Exception: {"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information."}
(exception itself) [System.InvalidOperationException]: {"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information."}
InnerException: {"345234775637544 is not a valid value for Int32."}
正如您所看到的,验证工作正常,但不会向用户产生错误消息。
我可以调整默认模型绑定器的行为,以便在这种情况下显示正确的错误消息吗?或者我必须编写一个自定义活页夹吗?
I've got the following model class (stripped for simplicity):
public class Info
{
public int IntData { get; set; }
}
Here's my Razor form that uses this model:
@model Info
@Html.ValidationSummary()
@using (Html.BeginForm())
{
@Html.TextBoxFor(x => x.IntData)
<input type="submit" />
}
Now if I enter a non-numeric data into the textbox, I receive a correct validation message, i.e.: "Value 'qqqqq' is not valid for field 'IntData'".
But if I enter a very long sequence of digits (like 345234775637544), I receive an EMPTY validation summary.
In my controller code, I see that ModelState.IsValid
is false
as expected, and ModelState["IntData"].Errors[0]
is as follows:
{System.Web.Mvc.ModelError}
ErrorMessage: ""
Exception: {"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information."}
(exception itself) [System.InvalidOperationException]: {"The parameter conversion from type 'System.String' to type 'System.Int32' failed. See the inner exception for more information."}
InnerException: {"345234775637544 is not a valid value for Int32."}
As you can see, the validation works normally, but doesn't yield an error message to the user.
Can I tweak the default model binder's behavior so that it shows a proper error message in this case? Or will I have to write a custom binder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是编写自定义模型绑定器:
可以在
Application_Start
中注册:One way would be to write a custom model binder:
which could be registered in
Application_Start
:将输入字段的 MaxLength 设置为 10 左右怎么样?我会结合在 IntData 上设置范围来做到这一点。当然,除非您希望允许用户输入 345234775637544。在这种情况下,您最好使用字符串。
How about setting MaxLength on the input field to 10 or so? I would do that in combination with setting a range on IntData. Unless of course you want allow a user to enter 345234775637544. In that case you're better off with a string.