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 }
);
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.
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.
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.
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.
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.
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