Evg*_*vin 7 asp.net-mvc custom-model-binder value-provider asp.net-mvc-3
在我的项目中,我希望允许用户以2种格式输入双值:使用','或'.' 作为分隔符(我对指数形式不感兴趣).默认值为分隔符'.' 不工作.我希望这种行为适用于复杂模型对象中的所有双属性(目前我使用的是包含标识符和值的对象集合).
我应该使用什么:价值提供商或模型粘合剂?请显示解决我的问题的代码示例.
Dar*_*rov 17
您可以使用自定义模型绑定器:
public class DoubleModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (result != null && !string.IsNullOrEmpty(result.AttemptedValue))
{
if (bindingContext.ModelType == typeof(double))
{
double temp;
var attempted = result.AttemptedValue.Replace(",", ".");
if (double.TryParse(
attempted,
NumberStyles.Number,
CultureInfo.InvariantCulture,
out temp)
)
{
return temp;
}
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Run Code Online (Sandbox Code Playgroud)
可以注册Application_Start:
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5277 次 |
| 最近记录: |