我剛剛在一個真實的項目中重新討論了這個問題,並最終找到了一個工作解決方案。正確的解決辦法是有類型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