问题的双重价值结合 [英] Problem with double values binding
本文介绍了问题的双重价值结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的项目,我想允许用户输入的双重价值在2格式:使用','或'。作为分隔符(我不感兴趣的指数形式)。通过与分隔符的默认值。不工作。
我想这种行为适用于在复杂的模型对象的所有属性双(目前我的对象的集合,包含标识符和值)。
In my project I want to allow users input double values in 2 formats: with using ',' or '.' as delimiter (I'm not interested in exponential form). By default value with delimiter '.' don't work. I want this behavior works for all double properties in complex model objects (currently I work with collections of objects, that contains identifiers and values).
我应该用什么:值提供或模型绑定?请,显示$ C解决我的问题$ C例子。
What i should use: Value Providers or Model Binders? Please, show code example of solving my problem.
推荐答案
您可以使用自定义的模型绑定:
You could use a custom model binder:
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);
}
}
这可能在的Application_Start
注册:
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
这篇关于问题的双重价值结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文