Bindung des ASP.NET MVC 1.0 und 2.0 Währungsmodells

Ich möchte eine Modellbindungsfunktion erstellen, damit ein Benutzer "," eingeben kann. etc für Währungswerte, die an einen doppelten Wert meines ViewModel gebunden sind.

Ich konnte dies in MVC 1.0 tun, indem ich einen benutzerdefinierten Modellordner erstellte. Seit dem Upgrade auf MVC 2.0 funktioniert diese Funktionalität jedoch nicht mehr.

Hat jemand Ideen oder bessere Lösungen für die Durchführung dieser Funktionalität? Eine bessere Lösung wäre die Verwendung von Datenanmerkungen oder benutzerdefinierten Attributen.

public class MyViewModel
{
    public double MyCurrencyValue { get; set; }
}

Eine bevorzugte Lösung wäre so etwas ...

public class MyViewModel
{
    [CurrencyAttribute]
    public double MyCurrencyValue { get; set; }
}

Unten ist meine Lösung für die Modellbindung in MVC 1.0.

public class MyCustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        object result = null;

        ValueProviderResult valueResult;
        bindingContext.ValueProvider.TryGetValue(bindingContext.ModelName, out valueResult);
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueResult);

        if (bindingContext.ModelType == typeof(double))
        {
            string modelName = bindingContext.ModelName;
            string attemptedValue = bindingContext.ValueProvider[modelName].AttemptedValue;

            string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator;
            string alternateSeperator = (wantedSeperator == "," ? "." : ",");

            try
            {
                result = double.Parse(attemptedValue, NumberStyles.Any);
            }
            catch (FormatException e)
            {
                bindingContext.ModelState.AddModelError(modelName, e);
            }
        }
        else
        {
            result = base.BindModel(controllerContext, bindingContext);
        }

        return result;
    }
}

Antworten auf die Frage(1)

Ihre Antwort auf die Frage