2011-12-16 54 views
1

我有一個自定義模型綁定器,我檢查字符串屬性是否爲null並將其替換爲空字符串。如何將asp.net mvc 3自定義模型綁定器GetPropertyValue屬性綁定器參數

我重寫BindProperty方法,但不知道如何從PropertyDescriptor的

GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, 
        <What should I pass for the IModelBinder?>); 

這裏獲得屬性值是BindProperty代碼

protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor) 
     { 
      if (propertyDescriptor.PropertyType == typeof(string)) 
      { 
       object s = GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, null); 
       if (s == null) 
       { 
        SetProperty(controllerContext, bindingContext, propertyDescriptor, ""); 
       } 
      } 
     } 
+0

你有沒有找到解決辦法? – 2017-10-04 08:47:42

回答

0

我使用不同的選項:

private static T? GetA<T>(ModelBindingContext bindingContext, string key) where T : struct, IComparable 
     { 
      if (String.IsNullOrEmpty(key)) return null; 
      //Try it with the prefix... 
      var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + key); 
      //Didn't work? Try without the prefix if needed... 
      if (valueResult == null && bindingContext.FallbackToEmptyPrefix) 
      { 
       valueResult = bindingContext.ValueProvider.GetValue(key); 
      } 
      if (valueResult == null) 
      { 
       return null; 
      } 
      return (T)valueResult.ConvertTo(typeof(T)); 
     } 

     private static DateTime? GetADateTime(ModelBindingContext bindingContext, string key) 
     { 
      if (String.IsNullOrEmpty(key)) return null; 
      //Try it with the prefix... 
      var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + key); 
      //Didn't work? Try without the prefix if needed... 
      if (valueResult == null && bindingContext.FallbackToEmptyPrefix) 
      { 
       valueResult = bindingContext.ValueProvider.GetValue(key); 
      } 
      if (valueResult == null) 
      { 
       return null; 
      } 
      return DateTime.Parse(valueResult.AttemptedValue, valueResult.Culture); 
     } 

     private static string GetValue(ModelBindingContext bindingContext, string key) 
     { 
      if (String.IsNullOrEmpty(key)) return null; 
      //Try it with the prefix... 
      var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "." + key); 
      //Didn't work? Try without the prefix if needed... 
      if (valueResult == null && bindingContext.FallbackToEmptyPrefix) 
      { 
       valueResult = bindingContext.ValueProvider.GetValue(key); 
      } 
      if (valueResult == null) 
      { 
       return null; 
      } 
      return valueResult.AttemptedValue; 
     } 

希望它能幫助!