2009-11-22 9 views

답변

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

정상적으로 파싱하는 것은 문제가 아니지만 "money"필드가 여러 개 있습니다. 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; 
    } 
} 

을 그것은 꽤 아니지만, 공장.

관련 문제