C# TryUpdateModel是否具有货币格式的值?
有没有办法让UpdateModel或TryUpdateModel将货币或货币格式的值(如$1200.00)解析为十进制,而不使用块?在调用这两种方法之前,您是否能够预先解析该值?如果是这样,您可以使用以下方法来执行此操作C# TryUpdateModel是否具有货币格式的值?,c#,asp.net-mvc,C#,Asp.net Mvc,有没有办法让UpdateModel或TryUpdateModel将货币或货币格式的值(如$1200.00)解析为十进制,而不使用块?在调用这两种方法之前,您是否能够预先解析该值?如果是这样,您可以使用以下方法来执行此操作 var provider = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone(); provider.CurrencySymbol = "$"; var x = deci
var provider = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
provider.CurrencySymbol = "$";
var x = decimal.Parse(
"$1,200",
NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
provider);
使用自定义模型活页夹
答案被授予Freddy Rios,因为他的链接为我提供了这样做的基础,但代码需要一些修改:
// http://www.crydust.be/blog/2009/07/30/custom-model-binder-to-avoid-decimal-separator-problems/
public class MoneyParsableModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
object result = null;
// Added support for decimals and nullable types - c.
if (
bindingContext.ModelType == typeof(double)
|| bindingContext.ModelType == typeof(decimal)
|| bindingContext.ModelType == typeof(double?)
|| bindingContext.ModelType == typeof(decimal?)
)
{
string modelName = bindingContext.ModelName;
string attemptedValue = bindingContext.ValueProvider[modelName].AttemptedValue;
// Depending on cultureinfo the NumberDecimalSeparator can be "," or "."
// Both "." and "," should be accepted, but aren't.
string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
string alternateSeperator = (wantedSeperator == "," ? "." : ",");
if (attemptedValue.IndexOf(wantedSeperator) == -1
&& attemptedValue.IndexOf(alternateSeperator) != -1)
{
attemptedValue = attemptedValue.Replace(alternateSeperator, wantedSeperator);
}
// If SetModelValue is not called it may result in a null-ref exception if the model is resused - c.
bindingContext.ModelState.SetModelValue(modelName, bindingContext.ValueProvider[modelName]);
try
{
// Added support for decimals and nullable types - c.
if (bindingContext.ModelType == typeof(double) || bindingContext.ModelType == typeof(double?))
{
result = double.Parse(attemptedValue, NumberStyles.Any);
}
else
{
result = decimal.Parse(attemptedValue, NumberStyles.Any);
}
}
catch (FormatException e)
{
bindingContext.ModelState.AddModelError(modelName, e);
}
}
else
{
result = base.BindModel(controllerContext, bindingContext);
}
return result;
}
}
它并不漂亮,但很管用。我认为这是一个很好的html助手,解析它通常不是一个问题,但我有许多“金钱”字段,如果可能的话,我不希望我的控制器在TryUpdateModel周围解析垃圾。@如果使用自定义模型绑定器,请参阅我答案中的链接。我有没有把堆栈难倒?它看起来不应该那么难?不像我希望的那么简单或优雅,但经过一些调整,它确实起了作用,所以谢谢你。我将张贴我的调整活页夹。