ASP.NET MVC默认绑定程序:整数过长,空验证错误信息。

8

我有以下模型类(简化后):

public class Info
{
    public int IntData { get; set; }
}

这是我的 Razor 表单,使用了这个模型:
@model Info
@Html.ValidationSummary()
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.IntData)
    <input type="submit" />
}

现在,如果我在文本框中输入非数字数据,我会收到一个正确的验证消息,即:“值 '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."}

正如您所看到的,验证功能正常,但没有向用户返回错误消息。

我能否调整默认模型绑定程序的行为,以便在这种情况下显示适当的错误消息?还是我必须编写自定义绑定程序?

2个回答

8

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

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());

谢谢,如果我无法调整默认的绑定器,我会选择这个解决方案。 - Zruty
如果您想要本地化字段名称而不是使用属性[Display(Name=...)],我建议将bindingContext.ModelName更改为bindingContext.ModelMetadata.DisplayName - Gh61

1
字段上设置MaxLength为10左右怎么样?我会将其与IntData的范围一起设置。当然,除非你想让用户输入345234775637544。在这种情况下,最好使用字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接