我刚刚在一个真实的项目中重新讨论了这个问题,并最终找到了一个工作解决方案。正确的解决办法是有类型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;
// 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;
}
}
然后在Global.asax.cs中的的Application_Start():
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
请注意,代码不是我的,我在Kristof Neirynck的博客here上发现它。我只编辑了几行,并为特定数据类型添加了活页夹,而不是替换默认活页夹。
我已经有这个,由于某种原因它不起作用。 – 2009-04-28 08:28:22
你的aspx页面中的标题怎么样?他们中的任何一个人是否有为文化设置的东西 – 2009-04-28 13:22:43
@尼克:没有,那里没有自定义的东西。 – 2009-05-11 19:25:52