Are there any pros/cons of using the following two alternatives in your action signature:
public ActionResult Action(int? x) // get MVC to bind null when no parameter is provided
{
if(x.HasValue)
{
// do something
}
}
OR
public ActionResult Action(int? x = null) // C# optional parameter (virtual overload)
{
if(x.HasValue)
{
// do something
}
}
Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression. Every parameter following an optional parameter in the procedure definition must also be optional.
What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value.
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.
I have never seen the second action signature in practice and can't see any usefulness of it.
The first one usually covers all the scenarios:
GET /somecontroller/action
), the value of the x argument will be null inside the actionGET /somecontroller/action?x=abc
), the value of the x argument will be null inside the action and the modelstate will be invalidGET /somecontroller/action?x=123
), then x will be assigned to it.In my examples I have used GET requests with query string parameters but obviously the same applies with other HTTP verbs and if x
was a route parameter.
You only need to specify the optional parameter value if it is going to be anything else other than null
.
MVC3 will automatically set null
as the value of your parameter if nothing is specified in the overload, or in the call to the Action.
However, its worth noting that if there are any non-optional parameters after this parameter in the signature, then null
would have to be specified in the call.
Therefore its best to put all optional params at the end of the signature.
Why not simplify controller action methods by removing unnecessary code branch and have this kind of code as seen here:
public ActionResult Index()
{
// do something when there's no id
}
[RequiresRouteValues("id")]
public ActionResult Index(int id)
{
// do something when id is present
}
This is of course possible, as long as you provide the very simple code for RequiresRouteValuesAttribute
action method selector. You can find code in this blog post that does exactly this.
By my opinion this is the best possible solution to this problem, because:
Anyway. All the details about this technique is explained in great detail in linked post.
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