C# ASP.NET MVC默认活页夹:整数太长,验证错误消息为空

C# ASP.NET MVC默认活页夹:整数太长,验证错误消息为空,c#,validation,asp.net-mvc-3,model-binding,defaultmodelbinder,C#,Validation,Asp.net Mvc 3,Model Binding,Defaultmodelbinder,我得到了以下模型类(为了简单起见被剥离): 这是我使用此模型的剃须刀表单: @model Info @Html.ValidationSummary() @using (Html.BeginForm()) { @Html.TextBoxFor(x => x.IntData) <input type="submit" /> } 如您所见,验证工作正常,但不会向用户生成错误消息 我可以调整默认模型绑定器的行为,以便在这种情况下显示正确的错误消息吗?或者我必须编写自定

我得到了以下模型类(为了简单起见被剥离):

这是我使用此模型的剃须刀表单:

@model Info
@Html.ValidationSummary()
@using (Html.BeginForm())
{
    @Html.TextBoxFor(x => x.IntData)
    <input type="submit" />
}
如您所见,验证工作正常,但不会向用户生成错误消息


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

一种方法是编写自定义模型活页夹:

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);
    }
}
可以在
应用程序\u Start
中注册:

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

将输入字段的MaxLength设置为10左右如何?我会结合在IntData上设置一个范围来实现这一点。当然,除非您希望允许用户输入34523475637544。在这种情况下,最好使用字符串。

谢谢,如果我无法调整默认绑定器,我将选择此解决方案。如果您希望在属性
[Display(Name=…)]
上使用本地化字段名,我建议将
bindingContext.ModelName
更改为
bindingContext.ModelMetadata.DisplayName
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);
    }
}
ModelBinders.Binders.Add(typeof(int), new IntModelBinder());