Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Parameter always filled

Tags:

c#

asp.net-mvc

I have a method in a controller:

public ActionResult SendNotification(Guid? id=null, SendNotification notification =null)

It responds to /Apps/SendNotification/{guid}?{SendNotification properties}

SendNotification is a model with multiple string properties.

My issue is that SendNotification is NEVER null. No matter how I call the action .NET seems to always instantiate an object of SendNotification (with all fields null).

I even tested with the System.Web.Http.FromUri and System.Web.Http.FromBody and it still does that.

Any ideas?

Note: this is not WebApi. This is regular MVC.

My project only have the default route:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
like image 683
rufo Avatar asked Nov 23 '12 15:11

rufo


People also ask

How do you pass an optional parameter?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.

Is it mandatory to specify a default value to optional parameter?

The following rules apply: 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.

Why are optional parameter added?

Optional Parameters are parameters that can be specified, but are not required. This allows for functions that are more customizable, without requiring parameters that many users will not need.

What is the optional parameter?

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.


1 Answers

That is Model Binding tricking you.

Since it doesn't find any Parameter to bind to the Model, all properties are null but the model is still instantiated by default.

Instead of checking for the Model to be null, check for one of your main property (such as ID) to be null.

like image 105
Yan Brunet Avatar answered Oct 21 '22 16:10

Yan Brunet