Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I assign a nullable integer to ViewBag, it un-nullables the value?

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)

like image 959
Mike Caron Avatar asked Oct 20 '22 11:10

Mike Caron


1 Answers

I would suggest that you create a view model which will give you full flexibility to make "MyInt" a null-able type for this.

Of course, the alternative would be to only set "MyInt" if it is not null...

public class MyController : Controller {
    public ActionResult Index(int? id) {
        if (id.HasValue)
        {
            ViewBag.MyInt = id;
        }
        return View();
    }
}

View:

@if (ViewBag.MyInt != null)
{
    <p>Has an Id</p>
}
else
{
    <p>Has no Id.</p>
}

Personally, I would go with a viewmodel as it's best practice, I rarely use ViewBag unless its for a VERY simple scenario.

like image 163
BenjaminPaul Avatar answered Oct 23 '22 06:10

BenjaminPaul