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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何在ASP.NET MVC控制器中设置十进制分隔符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在与 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,而不是替换默认的绑定。

原文链接:https://www.f2er.com/aspnet/252193.html

猜你在找的asp.Net相关文章