ASP.NET MVC 默认绑定器:整数太长,验证错误消息为空

发布于 2024-11-14 05:27:09 字数 1142 浏览 7 评论 0原文

我有以下模型类(为简单起见,已删除):

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.IsValidfalse 正如预期的那样,而 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

┈┾☆殇 2024-11-21 05:27:09

一种方法是编写自定义模型绑定器:

public class IntModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null)
        {
            int temp;
            if (!int.TryParse(value.AttemptedValue, out temp))
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format("The value '{0}' is not valid for {1}.", value.AttemptedValue, bindingContext.ModelName));
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
            }
            return temp;
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

可以在 Application_Start 中注册:

ModelBinders.Binders.Add(typeof(int), new IntModelBinder());

One way would be to write a custom model binder:

public class IntModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null)
        {
            int temp;
            if (!int.TryParse(value.AttemptedValue, out temp))
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, string.Format("The value '{0}' is not valid for {1}.", value.AttemptedValue, bindingContext.ModelName));
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
            }
            return temp;
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

which could be registered in Application_Start:

ModelBinders.Binders.Add(typeof(int), new IntModelBinder());
送舟行 2024-11-21 05:27:09

将输入字段的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文