在我已創建自定義模型粘結劑和IModelBinderProvider
處理貨幣asp.net的MVC應用程序時,貨幣被髮布到幾千格式的服務器,像$123,456.00
ASP.NET模型綁定基於屬性
我想調用自定義的模型綁定只有模型的屬性應用了某個屬性。下面是我的代碼
public interface IScrubberAttribute
{
object Scrub(string modelValue, out bool success);
}
public class CurrencyScrubberAttribute : Attribute, IScrubberAttribute
{
public object Scrub(string modelValue, out bool success)
{
// do something
}
}
public class ScrubbingModelBinder : DefaultModelBinder
{
IScrubberAttribute _attribute;
public ScrubbingModelBinder(Type type, IScrubberAttribute attribute)
{
_attribute = attribute as IScrubberAttribute;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// do something
}
}
public class ScrubbingModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if (modelType == typeof(decimal) || modelType == typeof(decimal?))
{
//??? ISSUE: the line below always returns null.
var attribute = modelType.GetCustomAttributes(typeof(CurrencyScrubberAttribute), false).FirstOrDefault();
if (attribute != null)
{
return new ScrubbingModelBinder(modelType, attribute as IScrubberAttribute);
}
}
return null;
}
}
我的模型
public class MyModel
{
[CurrencyScrubber]
public decimal? MyValue { get; set; }
}
我在應用程序啓動時註冊ScrubbingModelBinderProvider
所以得到調用它。
問題
在ScrubbingModelBinderProvider
我試圖找到,如果已申請了財產[CurrencyScrubber]
屬性;如果只是調用ScrubbingModelBinder
。
但是modelType.GetCustomAttributes()
方法無法找到或返回CurrancyScrubber
屬性。當我在調試模式下進行快速的手錶,該modelType.GetCustomAttributes()
方法返回3個屬性,但沒有一個類型CurrancyScrubber