代码之家  ›  专栏  ›  技术社区  ›  JeremyWeir

如何更新自定义ModelBinder以使用ASP.NET MVC RC2中已更改的ModelBindingContext.ValueProvider接口

  •  0
  • JeremyWeir  · 技术社区  · 16 年前

    我有一个自定义模型绑定器,它取一个逗号分隔的列表并清除所有空值,然后将其传递给默认模型绑定器。这在ASP.NET MVC预览2中有效,但当我升级到RC2时,下面的内容将无法编译,因为ValueProvider的接口只有getValue()方法,没有[]访问器。在绑定上下文中,我在下面所做的是否可以通过其他机制实现?我宁愿不必为这样一个简单的情况创建一个完整的模型活页夹。主要目标是当值绑定到列表<someEnum>时,将跳过任何空值。

    public class EnumListModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var result = bindingContext.ValueProvider[bindingContext.ModelName];
            string[] rawValues = (string[])result.RawValue;
            var newValues = new List<string>();
            foreach (string value in rawValues)
            {
                if (!String.IsNullOrEmpty(value))
                {
                    newValues.Add(value);
                }
            }
    
            string newValuesAttempted = String.Join(",", newValues.ToArray());
            // overwrite the ValueProviderResult with the cleaned up csv list
            // this is the part I'm not sure how to implement using the interface
            bindingContext.ValueProvider[bindingContext.ModelName] = 
               new ValueProviderResult(newValues.ToArray(), newValuesAttempted, result.Culture);
    
            return System.Web.Mvc.ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
        }
    }
    
    2 回复  |  直到 16 年前
        1
  •  1
  •   Craig Stuntz    16 年前

    到底是什么用错了 GetValue() 而不是 [] 在这里?它做同样的事情。但是 ValueProvider 现在是接口,接口不能有索引器。因此, 获取值() .

    将代码更改为:

    var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    

    不过,我有点惊讶的是,下一行的演员阵容竟然奏效了。似乎高度依赖于用户实际提交的内容和特定的属性类型。不过,这与你的问题无关。

        2
  •  0
  •   Community Mohan Dere    9 年前

    现在,没有多少解决方案可以说明ValueProvider集合是只读的。相反,我最终使用了一个定制的模型绑定器

    Is there a way to have the DefaultModelBinder ignore empty items when binding to a List<Enum>