我正在使用 ASP.NET MVC 3 开发网站。
属性
[DisplayName("Cost"), DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal Cost { get; set; }
查看
@Html.EditorFor(x => x.Cost)
View 将 Cost 呈现为 1000,00(例如)。问题是,验证需要一个点而不是逗号。如何输出 1000.00 而不是 1000,00?或者反转验证以接受逗号而不是点?
编辑。我在我的 web.config 中将全局化设置为 sv-SE(瑞典)。
最佳答案
您需要编写自定义模型绑定(bind)器来执行此操作。
/// <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 方法
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
关于c# - 在 View 模型中解析小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6994308/