在我的项目中,我希望允许用户以2种格式输入双值:使用’,’或’.’作为分隔符(我对指数形式不感兴趣).默认值为分隔符’.’不行.
我希望此行为适用于复杂模型对象中的所有双属性(目前我使用包含标识符和值的对象集合).
我希望此行为适用于复杂模型对象中的所有双属性(目前我使用包含标识符和值的对象集合).
解决方法
您可以使用自定义模型绑定器:
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());
原文地址:https://www.jb51.cc/aspnet/247591.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。