2014-11-04 26 views
1

我有我自己的空值整數和驗證文本的問題。c#特定模型和特定變量類型的自定義模型綁定器

基本上我想改變我自己的定製模型粘合劑當未提供

所以可爲空的INT從

"The value 'xxxxxxxxxxxxxxxxxxxx' is invalid" 

"Please provide a valid number" 

其中示出了驗證消息像這樣

public class IntModelBinder : IModelBinder 
    { 
     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
     { 
      var integerValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
      if (integerValue == null || integerValue.AttemptedValue == "") 
       return null; 

      var integer = integerValue.AttemptedValue; 

      bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider.GetValue(bindingContext.ModelName)); 
      try 
      { 
       return int.Parse(integer); 
      } 
      catch (Exception) 
      { 
       bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid, please provide a valid number.", bindingContext.ModelName)); 
       return null; 
      } 
     } 
    } 

現在我已經更新了我的global.asax.cs,所以所有可爲空的整數使用此模型聯編程序,但是我不希望所有可爲空的整數使用此,我只想要一個特定的模型使用它,並只使用我的在該模型中可爲空的模型中的模型綁定器。有沒有一種方法可以將此模型綁定器綁定到我的模型,並且只與可以爲null的int變量關聯?

我試圖用我的modebinder在我的模型,像這樣

[ModelBinder(typeof(IntModelBinder))] 
public class CreateQuoteModel 
{ 
    .... 
} 

但它不爲null的整數檢查,我想避免第三方插件

回答

1

您返回null在可空整數

if (integerValue == null || integerValue.AttemptedValue == "") 
    return null; 

所以你不能添加錯誤上可空整數的modelsatate。
此外,我建議你使用

int result=0; 
if(!int.TryParse(integer, out result)){ 
    bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid, please provide a valid number.", bindingContext.ModelName)); 
    return null; 
} 
return result; 

,而不是你的異常處理流程,以避免這種反模式

+0

謝謝你的回答,但是這並沒有解決我的實際問題 – Canvas 2014-11-04 16:05:23

1

當然,只要你有你的模型可空int和一個自定義所需的屬性這消息會工作?

相反,你可以使用的檢查長度的正則表達式匹配,然後鍵入

+0

這不起作用,因爲模型綁定接管所有的價值檢查,所以它錯過了將在模型中的所有字符串和日期時間 – Canvas 2014-11-04 16:04:54

+0

我不確定你的意思?您可以將屬性添加到爲您驗證它們的所有必填字段中。如果您需要自定義行爲,請創建自定義屬性並使用適當的接口。 – 2014-11-05 13:13:46