Here’s a quick ASP.NET MVC tip to help you be more productive and write cleaner code. We will see how to leverage C# 4’s optional and default parameters in our action methods for greatly simplifying our code while keeping it fully functional and error free.
Often you want to pass data to your controllers based on URL parameters. This can either be part of the URL itself in the case of route data or it can be part of the query string. In fact, this tip even works for input forms.
Let’s take a basic method which shows some census data, potentially filtered and sorted if that information is passed along, otherwise we’ll just show everything with a default sort.
This looks great, right? If you had a URL such as
It would work perfectly. But what if we omit sortAscending? Well, bool is a value type and doesn’t like missing data much:
I’m just guessing, but most users don’t love this page.
Yikes, we went from 1 line of code to many! However, (here’s the point of this post), let’s try that again with optional parameters:
Almost as simple as the naive version. However, you see making the request with and without data works perfectly! In fact, the data passed to GetDataAndResult are the same here as for the complex variant.
With Data (filtered and ordered):
Without Data (unfiltered and default order):
How about that? Hope you find that useful! You can download the code and try it for yourself here: OptionalParamsKennedy.zip