C# 4.0 从ASP.NET MVC 3升级到MVC 4,参数替换为route
我最近将我的项目从MVC3升级到MVC4,从那以后,我的一些操作参数被错误地传递 该行动具有以下特征:C# 4.0 从ASP.NET MVC 3升级到MVC 4,参数替换为route,c#-4.0,asp.net-mvc-4,asp.net-mvc-routing,C# 4.0,Asp.net Mvc 4,Asp.net Mvc Routing,我最近将我的项目从MVC3升级到MVC4,从那以后,我的一些操作参数被错误地传递 该行动具有以下特征: public JsonResult FooAction(int id, int id2, string name, string name2, List<Object1> templates, Dictionary<string, string> dictionary1, Dictionary<string, List<string>> dict
public JsonResult FooAction(int id, int id2, string name, string name2, List<Object1> templates, Dictionary<string, string> dictionary1, Dictionary<string, List<string>> dictionary2);
然后将字典2
设置为路线:
{key = "controller", value = "MyController"}
{key = "action", value = "MyAction"}
{key = "id", value = "123123"}
显然,我希望它只是一本空字典——有什么方法可以防止这种行为吗
[编辑]我应该提到,我使用的是默认路由行为:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
我通过在参数定义之前添加
[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);
以及在应用程序启动时:
ModelBinderProviders.BinderProviders.Add(new StringDictionaryModelBinderProvider());
但我还是被打败了
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());