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),我会收到一个 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."}

如您所见,验证工作正常,但不会向用户产生错误消息。

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

4

2 回答 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());
于 2011-06-09T08:58:01.317 回答
1

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

于 2011-06-10T02:30:03.177 回答