Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

c# - Passing Dictionary<string, object> to MVC Controller

I am attempting to pass a javascript object ( key value pairs ) to an MVC Controller action using AJAX.

The controller action has a Dictionary parameter that receives the object.

[HttpPost]
public ActionResult SearchProject(IDictionary<string, object> filter ...

When the object in question is empty ( meaning its value in javascript is {} ), I see the following in my debugger.

enter image description here

Why are the controller and action names automatically added to the Dictionary parameter ?

Using fiddler I am able to see what is being passed to my controller and I do not see these 2 values being passed ..

If the javascript object is not empty, then everything works fine

I am stumped..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appends two values because by default MVC registers such ValueProviderFactory:

public sealed class RouteDataValueProviderFactory : ValueProviderFactory

That returns implementation of IValueProvider - RouteDataValueProvider:

public sealed class RouteDataValueProvider : DictionaryValueProvider<object>
{
    // RouteData should use the invariant culture since it's part of the URL, and the URL should be
    // interpreted in a uniform fashion regardless of the origin of a particular request.
    public RouteDataValueProvider(ControllerContext controllerContext)
        : base(controllerContext.RouteData.Values, CultureInfo.InvariantCulture)
    {
    }
}

Basically it just binds Dictionary to route values for current route.

For example if you add such data to routes in RouteConfig:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Home", action = "Index", SomeSpecificRouteData = 42 }
);

Then your Dictionary will have 3 values - controller, action and SomeSPecificRouteData.

Another sample is that you can define such action:

public ActionResult Index(string action, string controller, int SomeSpecificRouteData)

and RouteDataValueProvider will pass data from your route as parameters to these method. In that way MVC binds parameters from routes to actual parameters for an actions.

If you want to remove such behavior you just need to iterate over ValueProviderFactories.Factories and remove RouteDataValueProviderFactory from it. But then your routes can have issues with parameters binding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...