有沒有什麼辦法可以讓UpdateModel或TryUpdateModel將貨幣或貨幣格式化的值(如$ 1,200.00)解析爲小數點而不會發出大塊?帶貨幣格式化值的TryUpdateModel?
5
A
回答
3
+0
並不像我希望的那麼簡單或優雅,但是通過調整它的實際效果,非常感謝。我會張貼我調整的粘結劑。 – 2009-12-01 21:48:56
1
你能夠在調用這些方法之前先解析數值嗎?如果是這樣,您可以使用以下方法做到這一點
var provider = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
provider.CurrencySymbol = "$";
var x = decimal.Parse(
"$1,200",
NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
provider);
2
答案被授予弗雷迪·里奧斯,因爲他的鏈接與底座要做到這一點給我提供了,但代碼需要一些固定起來:
// 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;
}
}
這是不漂亮,但它作品。
相關問題
- 1. 未格式化貨幣格式貨幣
- 2. 格式化貨幣
- 3. 格式化貨幣
- 4. 格式化貨幣
- 5. 格式化ASP.NET的GridView貨幣價值
- 6. 格式化字符串 - 貨幣值
- 7. 數字格式化函數值(貨幣)
- 8. Kendo UI貨幣格式化
- 9. 用C++格式化貨幣
- 10. 格式化AED貨幣
- 11. 格式化貨幣輸出
- 12. SQL貨幣格式化
- 13. C#貨幣格式化(「C2」)
- 14. ASP.net ListBox貨幣格式化
- 15. 貨幣格式化語言?
- 16. 貨幣格式化MVC
- 17. SQL to_char貨幣格式化
- 18. 貨幣格式化問題
- 19. Rails貨幣格式化
- 20. 帶貨幣符號的PHP貨幣格式
- 21. 以特定格式格式化貨幣
- 22. 格式貨幣
- 23. 貨幣格式
- 24. 貨幣格式
- 25. Java的貨幣格式化:強制使用的貨幣符號
- 26. 印度貨幣的PHP貨幣格式?
- 27. 如何將貨幣格式化爲近似美元的貨幣?
- 28. 將貨幣格式化爲asp.net mvc c中的貨幣#
- 29. 格式化Excel單元格(貨幣)
- 30. 格式化像貨幣,但沒有貨幣符號(C#)的雙精度值
我難倒了堆棧?它似乎不應該那麼辛苦? – 2009-11-23 15:49:32