Simone Simone - 1 month ago 9
C# Question

Avoid a Dictionary<string, T> from being bound to all query string parameters

In a C# ASP.NET MVC project, I have an action that receives a

Dictionary<string, T>
(
T
type is not really important, I think) as a parameter. I also want that parameter to be optional, with a default value of
null
.

However, if I don't specify that parameter when calling the action, I get it nonetheless, a dictionary filled with all query string key-value pairs.

The way I understand it, the MVC framework tries to bound the parameter to the query string, and because it is a dictionary with string keys the collection of key-value pairs in the query string is suitable data for the databinding mechanism.

But I need to be able to receive a
null
parameter anyway. And I am not allowed to explictly pass
null
in the route values either. How could I prevent the query string data binding from happening?

Answer

Instead of defining you model param as Dictionary create a model that would require more explicit binding

Something like

 ModelClass { 
    string SomeName {get;set;} 
    T Internal {get;set;}
}

public ActionResult YourAction(ModelClass boundInstance){}

This would certainly not get bound to random query string parameters. Do note however any model objects defined as optional parameters will never be null, they will just have empty data, even in your case if there were no query string parameters you would still end up with a constructed but empty Dic(). The default model binder calls any parameters empty constructor before attempting to bind data so the object is constructed even if no data can be bound to it.

Other option - If your only planning on getting the Dictionary data from a post you can add the attribute [FromBody] to the binding

public ActionResult YourAction([FromBody]Dictionary<string, T> boundInstance){}

Rant: Avoid using generic collection types as action parameters and you can avoid these issue entirely.

Comments