Edu*_*eni 3 asp.net asp.net-mvc modelbinders
我想在处理数字时扩展默认模型绑定以使其更加智能.当游戏中有逗号和小数点时,默认工作非常糟糕.
我正在尝试做一个新的活页夹
Public Class SmartModelBinder
Inherits DefaultModelBinder
Protected Overrides Sub SetProperty(controllerContext As ControllerContext, bindingContext As ModelBindingContext, propertyDescriptor As System.ComponentModel.PropertyDescriptor, value As Object)
If propertyDescriptor.PropertyType Is GetType(Decimal) Or propertyDescriptor.PropertyType Is GetType(Decimal?) Then
If value Is Nothing Then
value = 0
End If
End If
MyBase.SetProperty(controllerContext, bindingContext, propertyDescriptor, value)
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
但是此时已经转换了该值
如何扩展活页夹以从表单中获取字符串值并执行不同的转换?
那这个呢?
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder())
Run Code Online (Sandbox Code Playgroud)
和自定义活页夹.我想我不知道你是否可以用这种方式覆盖十进制绑定,但它适用于我自己的类型.
public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == null)
{
return base.BindModel(controllerContext, bindingContext);
}
// to-do: your parsing (get the text value from valueProviderResult.AttemptedValue)
return parsedDecimal;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3979 次 |
| 最近记录: |