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

asp.net-mvc – 如何在ASP.NET MVC控制器中设置十进制分隔符?

发布时间:2020-12-16 00:24:38 所属栏目:asp.Net 来源:网络整理
导读:我正在与 NerdDinner应用程序试图教自己ASP.NET MVC。然而,我偶然发现了全球化的问题,其中我的服务器以逗号作为小数分隔符来呈现浮点数,但虚拟地球地图需要它们带有点,这会导致一些问题。 我已经解决了the issue with the mapping JavaScript in my view
我正在与 NerdDinner应用程序试图教自己ASP.NET MVC。然而,我偶然发现了全球化的问题,其中我的服务器以逗号作为小数分隔符来呈现浮点数,但虚拟地球地图需要它们带有点,这会导致一些问题。

我已经解决了the issue with the mapping JavaScript in my views,但如果我现在尝试发布一个编辑的晚餐条目与点作为十进制分隔符控制器失败(抛出InvalidOperationException)更新模型(在UpdateModel()metod)。我觉得我必须在控制器的某个地方设置正确的文化,我在OnActionExecuting()中尝试过,但是没有帮助。

解决方法

我刚刚在一个真正的项目中重新审视了这个问题,最终找到了一个可行的解决方案。正确的解决方案是使用十进制类型的自定义模型绑定(如果使用十进制,则为十进制):
public class DecimalModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext,ModelBindingContext bindingContext)
    {
        object result = null;

        // Don't do this here!
        // It might do bindingContext.ModelState.AddModelError
        // and there is no RemoveModelError!
        // 
        // result = base.BindModel(controllerContext,bindingContext);

        string modelName = bindingContext.ModelName;
        string attemptedValue =
            bindingContext.ValueProvider.GetValue(modelName).AttemptedValue;

        // Depending on CultureInfo,the NumberDecimalSeparator can be "," or "."
        // Both "." and "," should be accepted,but aren't.
        string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
        string alternateSeperator = (wantedSeperator == "," ? "." : ",");

        if (attemptedValue.IndexOf(wantedSeperator) == -1
            && attemptedValue.IndexOf(alternateSeperator) != -1)
        {
            attemptedValue =
                attemptedValue.Replace(alternateSeperator,wantedSeperator);
        }

        try
        {
            if (bindingContext.ModelMetadata.IsNullableValueType
                && string.IsNullOrWhiteSpace(attemptedValue))
            {
                return null;
            }

            result = decimal.Parse(attemptedValue,NumberStyles.Any);
        }
        catch (FormatException e)
        {
            bindingContext.ModelState.AddModelError(modelName,e);
        }

        return result;
    }
}

然后在Application.Start()中的Global.asax.cs中:

ModelBinders.Binders.Add(typeof(decimal),new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?),new DecimalModelBinder());

请注意,代码不是我的,我实际上是在Kristof Neirynck的博客here中找到的。我刚刚编辑了几行,并添加了特定数据类型的binder,而不是替换默认的绑定。

(编辑:李大同)

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

    推荐文章
      热点阅读