2012-09-05 44 views
3

我最近将项目从MVC3升级到MVC4,此后,我的某些动作参数被错误传递。如果JSON调用传递一个空数组从ASP.NET MVC 3升级到MVC 4,参数被替换为路由

public JsonResult FooAction(int id, int id2, string name, string name2, List<Object1> templates, Dictionary<string, string> dictionary1, Dictionary<string, List<string>> dictionary2); 

"dictionary2":[] 

然后dictionary2设置为路由:

{key = "controller", value = "MyController"} 
{key = "action", value = "MyAction"} 
{key = "id", value = "123123"} 

很显然,我

该动作有这个签名'它喜欢它只是一个空的字典 - 有什么办法可以防止这种行为?

[编辑]我要指出,我使用的是默认的路由行为:

routes.MapRoute(
    "Default", 
    "{controller}/{action}/{id}", 
    new { controller = "Home", action = "Index", id = "" } 
); 

回答

0

我设法通过参数定义之前加入[Bind(Prefix = "dictionary2")]获得所需的行为,即

public JsonResult FooAction(int id, int id2, string name, string name2, List<Object1> templates, Dictionary<string, string> dictionary1, [Bind(Prefix = "dictionary2")] Dictionary<string, List<string>> dictionary2); 

但也击败了我。

或周围其他的方式,通过实现自己的ModelBinder

public class StringDictionaryModelBinderProvider: IModelBinderProvider 
{ 
    public IModelBinder GetBinder(Type modelType) 
    { 
     if (modelType == typeof (Dictionary<string, string>) || modelType == typeof (IDictionary<string, string>)) 
      return new StringDictionaryModelBinder(); 

     return null; 
    } 

    private class StringDictionaryModelBinder : DefaultModelBinder 
    { 
     public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
     { 
      bindingContext.FallbackToEmptyPrefix = false; 
      return base.BindModel(controllerContext, bindingContext); 
     } 
    } 
} 

和应用程序的启动:

ModelBinderProviders.BinderProviders.Add(new StringDictionaryModelBinderProvider()); 

不过还是甘拜下风。