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

在我的项目中,我希望允许用户以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());

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....