Consider this ASP.NET MVC 5 controller:
public class MyController : Controller {
public ActionResult Index(int? id) {
ViewBag.MyInt = id;
return View();
}
}
And this view:
<p>MyInt.HasValue: @MyInt.HasValue</p>
When I invoke the URL /my/
(with a null id), I get the following exception:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: Cannot perform runtime binding on a null reference
Conversely, if I pass an ID in (eg, /my/1
):
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'int' does not contain a definition for 'HasValue'
This suggests to me that ViewBag.MyInt
is not of type Nullable<int>
, but of either int
or null
.
Is this the ViewBag doing this? Or, is it something more fundamental about boxing Nullable types like this? Or, something else?
Is there another way to do this?
(I suppose that I could just change my check to ViewBag.MyInt == null
, but let's pretend I really needed a Nullable
type for some reason)