Tips for optional parameters to ASP.NET MVC action methods

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.

value-types

This looks great, right? If you had a URL such as

    /census/detailsvaltype/1?sortAscending=false

It would work perfectly. But what if we omit sortAscending? Well, bool is a value type and doesn’t like missing data much:

crash

I’m just guessing, but most users don’t love this page.

So we can make the parameters strings (no MVC conversion required, missing data can be detected, etc.) like this. But notice how ugly and complex the code becomesnullables-with-convert

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:

optinoal-params

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):
/census/detailsoptionaldefault/1?sortAscending=false

filtered-data

Without Data (unfiltered and default order):
/census/detailsoptionaldefault

with-no-data

How about that? Hope you find that useful! You can download the code and try it for yourself here: OptionalParamsKennedy.zip

Cheers,
@mkennedy

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s