我想创建模型绑定功能,因此用户可以输入“”“”。等,为结合到我的视图模型的一个双精度值的货币值。

我能够通过创建自定义模型粘合剂为此在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;
    }
}
有帮助吗?

解决方案

您可以尝试在电线之间的东西:

// 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)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top