2009-11-22 7 views
5

Existe-t-il un moyen d'obtenir UpdateModel ou TryUpdateModel pour analyser une valeur au format monétaire ou monétaire telle que 1 200,00 $ en une décimale sans souffler des morceaux?TryUpdateModel avec une valeur au format monétaire?

+0

Ai-je perdu la pile? Il ne semble pas que ça devrait être si difficile? –

Répondre

1

Êtes-vous capable d'analyser la valeur à l'avance avant d'appeler l'une de ces méthodes? Si oui, vous pouvez utiliser la méthode suivante pour le faire

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

Je pense que ce serait génial comme aide html – griegs

+0

Eh bien l'analyse normalement n'est pas un problème, mais j'ai un certain nombre de champs "d'argent" et je préfère pas d'ordure de mes contrôleurs analyser TryUpdateModel, si possible . –

+0

@cadmium utilise un classeur modèle personnalisé, voir le lien dans ma réponse. – eglasius

2

réponse a été attribué à Freddy Rios depuis son lien m'a fourni la base pour le faire, mais le code avait besoin de fixer en place:

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

Il est pas joli, mais travaux.

Questions connexes