我正在开发的ASP.NET MVC 3的站点。
I'm developing a site in ASP.NET MVC 3.
属性
[DisplayName("Cost"), DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal Cost { get; set; }
查看
@Html.EditorFor(x => x.Cost)
视图呈现费用作为1000,00(例如)。问题是,验证要求逗号的一个点来代替。我怎么能输出1000.00代替1000,00?或反向验证接受逗号,而不是一个点?
The view renders Cost as 1000,00 (for example). The problem is, validation demands a point instead of a comma. How can I output 1000.00 instead of 1000,00? Or reverse the validation to accept the comma instead of a point?
编辑。我给自己定的全球化在我的web.config中SV-SE(瑞典)。
Edit. I've set globalization in my web.config to sv-SE (Sweden).
您需要编写自定义模型绑定来做到这一点。
You'll need to write a Custom Model Binder to do this.
/// <summary>
/// http://haacked.com/archive/2011/03/19/fixing-binding-to-decimals.aspx
/// </summary>
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
ValueProviderResult valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
ModelState modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
CultureInfo.CurrentCulture);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
在您的Global.asax文件,添加以下到您的Application_Start方法
In your Global.asax file, add the following to your Application_Start Method
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
上一篇:为什么XmlDocument.LoadXml抛出System.Net.WebException?抛出、LoadXml、XmlDocument、WebException
下一篇:如何检查信号的状态,信号、状态