Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC Controller to accept value or null

I have a controller like this:

public ActionResult mycontroller(int status, DateTime start, DateTime end) 
{
   ...stuff
}

And I call it like this:

http://localhost:22200/mycontroller?status=1&start=18/03/2015&end=18/04/2015

However, half the time I need to call it like this:

http://localhost:22200/mycontroller?status=1

I would like to use same controller for both calls.

Is there way to change the controller to accept or not the parameters?

Ps: I don't want to have 2 controllers or a url like this

http://localhost:22200/mycontroller?status=1&start=null&end=null

Any help out there? Thanks a lot.

like image 710
KleberBH Avatar asked Mar 19 '15 01:03

KleberBH


1 Answers

Make start and end optional/nullable parameters as illustrated below.

ActionResult Action(int status, DateTime? start = null, DateTime? end = null)

The optional parameters will allow for the action to be called regardless of whether or not the start and end query string arguments are specified. When omitted, the default value null will be used. Thus both of the following URLs will be valid:

http://localhost:22200/mycontroller?status=1

http://localhost:22200/mycontroller?status=1&start=18/03/2015&end=18/04/2015

like image 83
Chris Baxter Avatar answered Sep 23 '22 06:09

Chris Baxter