I need to know how to account for an argument to my method being null
instead of an int
.
I have this method which is supposed to receive an int
[HttpGet]
public ActionResult UpdateUser(int userId){ }
However when ever the session times out and I log back in while in the middle of calling this method it receives a null
instead of an int
.
This causes this error:
The parameters dictionary contains a null entry for parameter 'userId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateUser(Int32)' in 'Controllers.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
I need a way to account for receiving a null
argument.
So far I have tried overloading the method with a nullable int type like this
[HttpGet]
public ActionResult UpdateUser(int? userId){ }
but this just ends up receiving every UpdateUser() call and converting the value to null
.
Any suggestions?
The signature for the overload, which won't be supplied the userId
is probably:
[HttpGet]
public ActionResult UpdateUser(){ }
i.e. no userId was supplied, rather than it being supplied with a null
value.
I say "probably" as it is possible that your request does in fact have the parameter/argument specified with no value.
If this is the case, you should probably use just the one signature:
[HttpGet]
public ActionResult UpdateUser(int? userId){ }
With a check...
if (userId.HasValue)
{
// ok... you can use userId.Value
}
else
{
// not ok...
}