2009-11-22 6 views

答えて

3

カスタムモデルバインダーを使用してください。

An example of using one to parse a decimals differently

+0

私が望んでいたほどシンプルでエレガントではありませんでしたが、実際にはうまくいきましたので、ありがとうございました。私は私の微調整されたバインダーを投稿します。 –

1

これらのメソッドのいずれかを呼び出す前に値を解析することはできますか?その場合は、次の方法を使用してください。

var provider = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone(); 
    provider.CurrencySymbol = "$"; 
    var x = decimal.Parse(
     "$1,200", 
     NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, 
     provider); 
+0

これは私がhtmlヘルパーとして素晴らしいと思います – griegs

+0

よく解析するのは問題ではありませんが、私はいくつかの「お金」フィールドを持っていますし、可能ならば、私のコントローラの迷惑メールをTryUpdateModelのまわりで解析しません。 –

+0

@cadmiumカスタムモデルのバインダーを使用して、私の答えのリンクを参照してください。 – eglasius

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; 
    } 
} 

それはきれいではありませんが、それ働く

関連する問題