更具体地说,针对mvc模型绑定,构建查询字符串的方式是:
/somemethod?model[0].Key=1&model[0].Value=One&model[1].Key=2&model[1].Value=Two
自定义绑定器只需遵循默认模型绑定器即可。
public class QueryStringToDictionary<TKey, TValue> : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var modelBindingContext = new ModelBindingContext
{
ModelName = bindingContext.ModelName,
ModelMetadata = new ModelMetadata(new EmptyModelMetadataProvider(), null,
null, typeof(Dictionary<TKey, TValue>), bindingContext.ModelName),
ValueProvider = new QueryStringValueProvider(controllerContext)
};
var temp = new DefaultModelBinder().BindModel(controllerContext, modelBindingContext);
return temp;
}
}
在模型中应用自定义模型绑定器。
public ActionResult SomeMethod(
[ModelBinder(typeof(QueryStringToDictionary<int, string>))] Dictionary<int, string> model)
{
return Content("Test");
}