5

ユーザーが「,」「.」を入力できるように、モデル バインディング機能を作成したいと考えています。私のViewModelの二重値にバインドする通貨値など。

カスタム モデル バインダーを作成することで MVC 1.0 でこれを行うことができましたが、MVC 2.0 にアップグレードしてから、この機能は機能しなくなりました。

この機能を実行するためのアイデアやより良い解決策はありますか? より良い解決策は、データ注釈またはカスタム属性を使用することです。

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

好ましい解決策は次のようなものです...

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

以下は、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;
    }
}
4

1 に答える 1

7

次の行の中から何かを試すことができます。

// Just a marker attribute
public class CurrencyAttribute : Attribute
{
}

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


public class CurrencyBinder : DefaultModelBinder
{
    protected override object GetPropertyValue(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        PropertyDescriptor propertyDescriptor, 
        IModelBinder propertyBinder)
    {
        var currencyAttribute = propertyDescriptor.Attributes[typeof(CurrencyAttribute)];
        // Check if the property has the marker attribute
        if (currencyAttribute != null)
        {
            // TODO: improve this to handle prefixes:
            var attemptedValue = bindingContext.ValueProvider
                .GetValue(propertyDescriptor.Name).AttemptedValue;
            return SomeMagicMethodThatParsesTheAttemptedValue(attemtedValue);
        }
        return base.GetPropertyValue(
            controllerContext, 
            bindingContext, propertyDescriptor, 
            propertyBinder
        );
    }
}

public class HomeController: Controller
{
    [HttpPost]
    public ActionResult Index([ModelBinder(typeof(CurrencyBinder))] MyViewModel model)
    {
        return View();
    }
}

アップデート:

以下はバインダーの改善です (TODO前のコードのセクションを参照)。

if (!string.IsNullOrEmpty(bindingContext.ModelName))
{
    var attemptedValue = bindingContext.ValueProvider
        .GetValue(bindingContext.ModelName).AttemptedValue;
    return SomeMagicMethodThatParsesTheAttemptedValue(attemtedValue);
}

コレクションを処理するには、バインダーを登録する必要があります。これApplication_Startは、リストを次のように装飾することができなくなるためModelBinderAttributeです。

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(MyViewModel), new CurrencyBinder());
}

そして、あなたの行動は次のようになります:

[HttpPost]
public ActionResult Index(IList<MyViewModel> model)
{
    return View();
}

重要な部分を要約すると:

bindingContext.ValueProvider.GetValue(bindingContext.ModelName)

このバインダーのさらなる改善ステップは、検証 (AddModelError/SetModelValue) を処理することです。

于 2010-03-16T10:52:40.430 に答える