MVC 2,IModelBinder和ValueProvider发生了变化

Mos*_*ose 5 imodelbinder asp.net-mvc-2

我正在尝试迁移到ASP.Net MVC 2并遇到一些问题.这是一个:我需要直接绑定一个字典作为视图的结果.

在ASP.Net MVC 1中,它使用自定义IModelBinder完美地工作:

/// <summary>
/// Bind Dictionary<int, int>
/// 
/// convention : <elm name="modelName_key" value="value"></elm>
/// </summary>
public class DictionaryModelBinder : IModelBinder
{
    #region IModelBinder Members

    /// <summary>
    /// Mandatory
    /// </summary>
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        IDictionary<int, int> retour = new Dictionary<int, int>();

        // get the values
        var values = bindingContext.ValueProvider;
        // get the model name
        string modelname = bindingContext.ModelName + '_';
        int skip = modelname.Length;

        // loop on the keys
        foreach(string keyStr in values.Keys)
        {
            // if an element has been identified
            if(keyStr.StartsWith(modelname))
            {
                // get that key
                int key;
                if(Int32.TryParse(keyStr.Substring(skip), out key))
                {
                    int value;
                    if(Int32.TryParse(values[keyStr].AttemptedValue, out value))
                        retour.Add(key, value);
                }
            }
        }
        return retour;
    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

它与一些显示数据字典的智能HtmlBuilder配合使用.

我现在遇到的问题是ValueProvider不再是Dictionary <>,它是一个IValueProvider,只允许获取名称已知的值

public interface IValueProvider
{
    bool ContainsPrefix(string prefix);
    ValueProviderResult GetValue(string key);
}
Run Code Online (Sandbox Code Playgroud)

这真的不酷,因为我无法执行我的智能解析...

题 :

  1. 是否有另一种获取所有密钥的方法?
  2. 您是否知道将HTML元素集合绑定到Dictionary的另一种方法

谢谢你的建议

O.

Fel*_*ima 1

我认为在 MVC 2 中您将无法再这样做。
或者,您可以扩展 DefaultModelBinder 并重写其虚拟方法之一(例如 GetModelProperties),然后更改 ModelBindingContext 内的 ModelName。另一种选择是为您的字典类型实现自定义 MetadataProvider,您也可以在那里更改模型名称。