When I assign an integer with a null value in the ViewBag, is it an un-nullable value?

Consider this ASP.NET MVC 5 controller:

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

And this look:

<p>MyInt.HasValue: @MyInt.HasValue</p>

When I call the URL /my/(with a null identifier), 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

And vice versa, if I pass the identifier to (e.g. /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 tells me that it ViewBag.MyIntdoes not have a type Nullable<int>, but either int, or null.

Does this viewbag do this? Or, it is something more fundamental with regard to boxing. Zero types like this? Or something else?

Is there any other way to do this?

(I suppose I could just change my check for ViewBag.MyInt == null, but let's say I really need a type Nullablefor some reason)

+4
3

, , , "MyInt" .

, "MyInt", null...

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

:

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

viewmodel, , ViewBag, .

+3

, .

<p>MyInt.HasValue: @(((int?)MyInt).HasValue)</p>

.

0

ViewBag - DynamicViewDataDictionary (. ASP.NET).

Nullable - , ViewBag. . , , MSDN. , " , CLR Nullable"...

ViewBag null. , Nullable. :

@if (ViewBag.MyInt != null)
{
    <p>@ViewBag.MyInt</p>
}

:

<p>@ViewBag.MyInt</p>

MyInt ViewBag, . Nullable, int.

0

Source: https://habr.com/ru/post/1534283/


All Articles