ASP.NET MVC默认的binder:太长的int,空验证错误信息

Zru*_*uty 7 c# validation defaultmodelbinder model-binding asp.net-mvc-3

我有以下模型类(为简单起见而剥离):

public class Info
{
    public int IntData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我使用此模型的Razor表单:

@model Info
@Html.ValidationSummary()
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.IntData)
    <input type="submit" />
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我在文本框中输入非数字数据,我会收到一条正确的验证消息,即:"值'qqqqq'对字段'IntData'无效".

但是如果我输入一个很长的数字序列(如345234775637544),我会收到一个EMPTY验证摘要.

在我的控制器代码中,我看到的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."}
Run Code Online (Sandbox Code Playgroud)

如您所见,验证工作正常,但不会向用户发出错误消息.

我是否可以调整默认模型绑定器的行为,以便在这种情况下显示正确的错误消息?或者我是否必须编写自定义绑定器?

Dar*_*rov 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

可以注册Application_Start:

ModelBinders.Binders.Add(typeof(int), new IntModelBinder());
Run Code Online (Sandbox Code Playgroud)