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
);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With