7

我有以下的模型类(剥离为简单起见):ASP.NET MVC默认联:太长整数,空验证错误消息

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

这里是我的剃刀形式使用此模型:

@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."} 

正如你所看到的,确认工作正常,但不会产生一个错误信息用户。

我可以调整默认模型联编程序的行为,以便在此情况下显示正确的错误消息吗?或者我将不得不编写一个自定义联编程序?

回答

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

谢谢,如果我无法调整默认绑定器,我会选择此解决方案。 – Zruty 2011-06-09 09:11:33

+0

如果你想通过属性'[Display(Name = ...)]'来获得本地化的fieldname,''我建议把'bindingContext.ModelName'改为'bindingContext.ModelMetadata.DisplayName'。 – Gh61 2015-03-31 13:38:06

1

如何输入字段设置的MaxLength到10个左右?我会在IntData上设置一个范围。除非你想允许用户输入345234775637544。在这种情况下,你最好用一个字符串。

+0

现在,这是我没有想到的:)谢谢。 – Zruty 2011-06-10 09:07:16

+0

多数民众赞成在智能:)! – frictionlesspulley 2011-11-03 17:16:50