逗号小数点分隔符是由ASP.NET MVC模型绑定忽略 [英] Comma decimal separator is ignored by ASP.NET MVC model binder
本文介绍了逗号小数点分隔符是由ASP.NET MVC模型绑定忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从http请求120,12在双模式转换为12012。我读了ASP.NET MVC应该处理这样的事情,但我不能使它工作。
120,12 from http request is converted to 12012 in double model. I read that ASP.NET MVC should handle such things but I couldn't make it work
请求:
Accept-Language:da,en;q=0.8,ru;q=0.6,en-US;q=0.4
...
Price: "120,12"
操作方法的模式包括:公共双价{搞定;组; }
Action method' model contains: public double Price { get; set; }
在行动:
var uICulture = Thread.CurrentThread.CurrentUICulture; // {da}
var culture = Thread.CurrentThread.CurrentCulture; // {da-DK}
本地化在的Global.asax <控制/ code>
Application_AcquireRequestState
里面的:
var cultureInfo = new CultureInfo("da");
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
在您的帮助!
推荐答案
您可以编写一个自定义的模型绑定
You can write a custom model binder.
public class DecimalModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName);
var modelState = new ModelState {Value = valueResult};
object actualValue = null;
try
{
//Check if this is a nullable decimal and a null or empty string has been passed
var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType &&
string.IsNullOrEmpty(valueResult.AttemptedValue));
//If not nullable and null then we should try and parse the decimal
if (!isNullableAndNull)
{
actualValue = decimal.Parse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture);
}
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
}
只要改变CultureInfo.CurrentCulture到所述一个的用户在decimal.Parse声明已经选择。然后注册在启动新的ModelBinder的。
Just change the CultureInfo.CurrentCulture to that of the one the user has selected in the decimal.Parse statement. Then register the new modelbinder at startup.
这篇关于逗号小数点分隔符是由ASP.NET MVC模型绑定忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文