Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Parameters in C# - Defaulting a user-defined Class to null

Tags:

c#

asp.net

In a C# controller, I have a function defined with an optional parameter which is set to default to null (see code example below). The first time the page loads, the function is called and the filter is passed in as an initialized object, despite the default value being null. I would like it to be null the first time the page loads. Is there a way to do this?

public ActionResult MyControllerFunction(CustomFilterModel filter = null)
{
    if (filter == null)
         doSomething(); // We never make it inside this "if" statement.

    // Do other things...
}

This action is resolved by the following route definition:

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Project", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
like image 571
yeapiekiyay Avatar asked Jul 23 '14 19:07

yeapiekiyay


Video Answer


1 Answers

The default model binder (DefaultModelBinder) will create an instance of CustomFilterModel and then attempt to fill the object with data from the request. Even if the default model binder finds no properties of your model in the request it will still return the empty model, hence you will never get a null object for your parameter. There seems to be nothing in the source [1] that will return a null model.

[1] https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/DefaultModelBinder.cs

like image 171
JohnCampbellJr Avatar answered Oct 11 '22 17:10

JohnCampbellJr