ASP.Net Core Complex Model Binding

Erick Gallani
4 min readJun 4, 2022

--

Did you ever face a situation where you have a search UI, like a front-end application, that has a data table and you need to support a complex query construction that can contain Free Text search, Sorting of multiple columns, and extra filters and query parameters starts to look a nightmare on your controllers?

ASP.Net offers great flexibility, extensibility, and customization to graceful handle these situations.

The problem

Let’s imagine the scenario where you need to create a Search API to provide data to a Data Table in a UI, and this search needs to allow free text search, multiple sortings for different properties, and add any other extra piece of filtering property.

API Contract

So you have an API Contract something like this.

{
"term": "cool stuff",
"countryAlphaCode2": "US",
"sorts": [
"asc|percentualDelivered",
"desc|percentualPaid"
]
}

So as you can see there, the sort will be sent to the API following the pattern {direction[asc|desc]}|{propertyName} which is a fair pattern and easy for URL query parameters to send over.

But the problem with this approach is if we just received the parameters as pure strings on the controller, this will pollute our controller, we’ll not use the advantage of the binding pipeline for fail-fast for example, and it will demand a propagation of raw string to be parsed and interpreted.

Another problem is that every time a new query parameter is introduced a lot of changes will be required on the controller action signature and the code inside.

Controller using primitives only

How the request for this example above would look like?

https://my-api.com/search?term=cool stuff&countryAlphaCode2=US&sorts[0]=asc|percentualDelivered&sorts[1]=desc|percentualPaid

Parsed URI request

The query parameter actually needs to be encoded before the request, so you will see something like the below.

https://my-api.com/search?term=cool%20stuff&countryAlphaCode2=US&sorts%5B0%5D=asc%7CpercentualDelivered&sorts%5B1%5D=desc%7CpercentualPaid

Now let’s take a step forward and create a class that will represent the query parameters

Search query parameter class

As you may notice instead of an array of strings in the Sorts we’ll use a class to interpret the string pattern {direction[asc|desc]}|{propertyName} and create a complex type instead of an array of primitives (strings).

The problem here is that if we just add a class there will not work quite well because by default a complex type model binder bind values direct to the properties, by Microsoft documentation

A complex type must have a public default constructor and public writable properties to bind. When model binding occurs, the class is instantiated using the public default constructor.

Which in this case will not help us too much because having a class with a public setter that holds an array of strings will bring no advantages at all.

Wouldn’t be great if we could have a class that will hold all the “sort” pattern parse logic, receiving the sort string in the constructor and building it in a complex meaningful type with validations and more enriched values?

Well, in fact, we can with the Custom Model Binding.

So let’s create a ModelBinder class and also our Sort class.

Sort Model Binder

Sort Query class

And this is how it works.

When data comes from an HTTP request ASP.Net framework will loop over all the parameters in the controller action signature looking through the available sources in the HTTP request and trying to find matching names between the parameters and the query params in our example (remember parameters can come [FromQuery], [FromBody], [FromRoute], [FromForm], and [FromHeader]) and try to parse the received value to the controller parameter type.

So if we want .Net to do more fancy work for us we need to instruct the framework on how to do it, and that’s basically what the code above is doing.

SortModelBinder is used on the Sort class declaration [ModelBinder(BinderType = typeof(SortModelBinder))] to instruct .Net that, for building the Sort class it needs to run our custom binding algorithm and our algorithm will instantiate a Sort class for each string value of the Sorting array received on the request.

So now we can do a lot of complex work delegated to the framework, like on the Sort class where we receive a string in the constructor and actually do a series of validations for a fail-fast approach, convert the string direction “asc” and “desc” to an enum “Ascending” and “Descending”, standardizing the string to lower case, respecting the single principle from SOLID by creating classes that only have one reason to change, and easy to unit test.

And finally….

Controller using a complex type model binding

Is way better don’t you think? Cleaner and a better design to use the strength of the framework in our favor.

Conclusion

As you can see ASP.Net is a very powerful and flexible framework with a lot of extensible features to make your code more readable, testable, flexible, and enriched.

Reference

Microsoft Documentation: https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-6.0

In this post, I’ll cover how can we use this alongside Entity Framework Core and Linq Expression Tree to easily add sorting dynamically to a Queryable object using this binding we just created interacting with the Database

Was this useful to you? I’m keen to hear your thoughts.

--

--

Erick Gallani

AWS Certified Developer | Software Engineer by passion, more than 10 years writing software and fixing bugs.