加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 双值绑定问题

发布时间:2020-12-16 04:13:22 所属栏目:asp.Net 来源:网络整理
导读:在我的项目中,我希望允许用户以2种格式输入双值:使用’,’或’.’作为分隔符(我对指数形式不感兴趣).默认值为分隔符’.’不行. 我希望此行为适用于复杂模型对象中的所有双属性(目前我使用包含标识符和值的对象集合). 我应该使用什么:价值提供商或模型粘合
在我的项目中,我希望允许用户以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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读