MVC 5 十进制?带小数分隔符的字段编辑器
MVC5 decimal? field editfor with decimal seperator
我的模式中有一个小数字段。
public partial class MyModel
{
public decimal? BudgetAantalDecimal { get; set; }
}
我用
在我的表格中显示了这个
@Html.EditorFor(model => model.BudgetAantalDecimal, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
当我填写值 100 时,该字段已填写到模型中。当我填写值 100.66 时,该值在我的模型中为空。
当我将语言设置从荷兰语更改为美国格式时,我可以使用值 100.66。我的客户在 Windows 中设置了荷兰语设置。我该如何解决这个问题?
您需要添加自定义模型活页夹来处理小数时不断变化的标点符号。 This blog 逐步介绍,但我会在这里重新创建一些,以防 link 中断。
首先,您需要创建活页夹:
public class DecimalModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
var 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;
}
}
在那之后,您需要做的就是将它添加到您的配置中,以便它知道:
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
// All that other stuff you usually put in here...
}
我的模式中有一个小数字段。
public partial class MyModel
{
public decimal? BudgetAantalDecimal { get; set; }
}
我用
在我的表格中显示了这个@Html.EditorFor(model => model.BudgetAantalDecimal, new { htmlAttributes = new { @class = "form-control decimal-small inline" } })
当我填写值 100 时,该字段已填写到模型中。当我填写值 100.66 时,该值在我的模型中为空。
当我将语言设置从荷兰语更改为美国格式时,我可以使用值 100.66。我的客户在 Windows 中设置了荷兰语设置。我该如何解决这个问题?
您需要添加自定义模型活页夹来处理小数时不断变化的标点符号。 This blog 逐步介绍,但我会在这里重新创建一些,以防 link 中断。
首先,您需要创建活页夹:
public class DecimalModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
var modelState = new ModelState { Value = valueResult };
var 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;
}
}
在那之后,您需要做的就是将它添加到您的配置中,以便它知道:
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
// All that other stuff you usually put in here...
}