asp.net中的逗号小数分隔符mvc 5

我拼命试图让asp.net使用逗号符号作为小数分隔符,但这似乎要困难得多……

我已经完成了本教程中的所有内容http://www.asp.net/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view

在root web配置中尝试了这个

   

介绍了jQuery代码 – 全球化似乎有效。

我正在使用带有模型视图控制器的get请求,看起来像这样

 public class SearchCalcViewModel { public SearchCalcViewModel() { } public IEnumerable Calculations { get; set; } [Display(Name="Name")] public string Name { get; set; } [Display(Name="Height")] public decimal? Height { get; set; } } 

在maincontroller中调用get请求 – 这样就加强了我的假设,即jquery文化依赖validation正在工作,而.net文化中的某些东西也是错误的,即使Thread.CurrentTHread.CurrentCulture / CurrentUICulture也正确设置了。

当我尝试填充3,0作为高度时,我收到以下错误消息:

值“3,0”对高度无效。

这是我的观点的导入部分:

 @using (Html.BeginForm("Search", "Main", FormMethod.Get)) 
@Html.LabelFor(m => m.Height, new { @class = "col-md-2 control-label" })
@Html.TextBoxFor(m => m.Height, new { @class = "form-control"}) @Html.ValidationMessageFor(m => m.Height)
}

这是我的MainController:

 public ActionResult Search(SearchCalcViewModel searchViewModel) { searchViewModel.Products = db.Products; searchViewModel.Calculations = from c in db.Calculations select c; if (searchViewModel.Height.HasValue) { searchViewModel.Calculations = searchViewModel.Calculations.Where(c => c.Length == searchViewModel.Height); } return View(searchViewModel); } 

我已经进入了模型状态,不知何故,文化与我现在的文化不同

错误的文化

您的值为3,0 ,这不是有效的十进制类型值。 它应该是3.0 " comma(,) with dot(.)替换" comma(,) with dot(.)

编辑:创建自己的模型绑定器。

 public class DecimalModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); return valueProviderResult == null ? base.BindModel(controllerContext, bindingContext) : Convert.ToDecimal(valueProviderResult.AttemptedValue); } } 

在Application_Start文件中添加这些行。

 ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder()); 

我认为现在应该可行了。 🙂

我知道已经老了,但我有同样的问题(使用es-AR),我发现了一个更好的解决方案,你可以简单地做到这一点:

 void Application_AcquireRequestState(object sender, EventArgs e) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(HttpContext.Current.Session["userCulture"]); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(HttpContext.Current.Session["userCulture"]); } 

在Global.asax上

此代码在模型绑定之前运行,因此您可以将文化信息设置为线程,并且您还可以访问会话变量(对于特定的用户文化)