我正在使用NerdDinner应用程序,试图自学ASP.NET MVC。然而,我偶然发现了全球化的一个问题,我的服务器用逗号作为小数点分隔符显示浮点数,但Virtual Earth地图需要它们带点,这会导致一些问题。
我已经解决了the issue with the mapping JavaScript in my views,但如果我现在尝试发布一个编辑过的晚餐条目,并将点作为小数点分隔符,则当更新模型(在UpdateModel()
方法中)时,控制器将失败(抛出InvalidOperationException
)。我觉得我也必须在控制器中的某个地方设置适当的区域性,我在OnActionExecuting()
中尝试了一下,但这没有帮助。
发布于 2011-02-25 20:51:14
我刚刚在一个真实的项目中重新考虑了这个问题,并最终找到了一个可行的解决方案。正确的解决方案是为类型decimal
(以及decimal?
,如果您正在使用它们)提供一个自定义模型绑定:
using System.Globalization;
using System.Web.Mvc;
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;
// in decimal? binding attemptedValue can be Null
if (attemptedValue != null)
{
// 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, StringComparison.Ordinal) == -1
&& attemptedValue.IndexOf(alternateSeperator, StringComparison.Ordinal) != -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上找到的。我只是编辑了几行代码,并为特定的数据类型添加了绑定器,而不是替换默认的绑定器。
发布于 2009-04-27 13:32:23
在你的web.config中设置这个
<system.web>
<globalization uiCulture="en" culture="en-US" />
您使用的服务器似乎安装了使用逗号而不是小数位的语言。您可以将区域性调整为以设计应用程序的方式使用逗号的区域性,例如en-US。
https://stackoverflow.com/questions/793459
复制相似问题