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

相關問題