Changes to MVC 2, IModelBinder, and ValueProvider

I am trying to upgrade to ASP.Net MVC 2 and solve some problems. Here is one of them: I needed to attach the Dictionary directly as a result of the viewing message.

In ASP.Net MVC 1, it worked perfectly using custom 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
}

He was paired with some intelligent HtmlBuilder that displayed a data dictionary.

The problem that I am facing now is that ValueProvider is no longer a dictionary <>, it is IValueProvider, which allows you to get values ​​whose name is known

public interface IValueProvider
{
    bool ContainsPrefix(string prefix);
    ValueProviderResult GetValue(string key);
}

This is really not cool, as I cannot do my intellectual parsing ...

Question:

  • ?
  • HTML

.

+5
2

, MVC 2.
, DefaultModelBinder , GetModelProperties, ModelName ModelBindingContext. MetadataProvider , .

+1

"", , . , System.Web.Mvc.DefaultValueProvider. RouteData, ( ). ( , ), .

private static IEnumerable<string> GetKeys(ControllerContext context)
{
    List<string> keys = new List<string>();
    HttpRequestBase request = context.HttpContext.Request;
    keys.AddRange(((IDictionary<string,
        object>)context.RouteData.Values).Keys.Cast<string>());
    keys.AddRange(request.QueryString.Keys.Cast<string>());
    keys.AddRange(request.Form.Keys.Cast<string>());
    return keys;
}

:

foreach (string key in GetKeys(controllerContext))
{
    // Do something with the key value.
}
+2

All Articles