Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my ViewData be null, but expandable in the debugger?

Just came across an interesting effect while debugging a View. The scenario is easy to reproduce - I have a breakpoint in a View, in the Watch window I add ViewBag.ViewData and the value is null. However, if I just add ViewBag and expand the object, I can see the ViewData and it is not null. I can also successfully expand it and see its properties.

Can anyone explain whether it's a bug or what causes this behavior?

ViewBag.ViewData in Watch window

EDIT

ViewBag.ViewData is actually null. E.g. if I have this code in the View:

if (ViewBag.ViewData == null)
{
    <span>ViewBag.ViewData is null</span>
}

it displays the span. So the weird part is that I can expand it in the watch window and see the properties.

EDIT2

In response to @Darin Dimitrov's answer - I tried to reproduce this behavior with a custom test class and I get a RuntimeBinderException when trying to access the private property: 'SomeClass.SomeProperty' is inaccessible due to its protection level:

public class SomeClass
{
    private string SomeProperty;
}

dynamic dynamicObject = new SomeClass();
if (dynamicObject.SomeProperty == null)
{
    Console.WriteLine("dynamicObject.SomeProperty is null");
}

In this case, shouldn't I be getting the same exception when accessing ViewBag.ViewData in the View (the line with if (ViewBag.ViewData == null))?

like image 321
Yakimych Avatar asked Apr 28 '11 12:04

Yakimych


1 Answers

What you see in the debugger/watch window is the private ViewData property of the ViewBag. When you do the test in the view you obviously have no access to this private field and you get null because there is no corresponding public property.

Now do the following test in the view:

@if (null == ViewBag
         .GetType()
         .GetProperty("ViewData", BindingFlags.Instance | BindingFlags.NonPublic)
         .GetValue(ViewBag, null)
)
{
    <span>ViewBag.ViewData is null</span>
}

and you won't see the span.

Of course all this is very funny but when it comes to writing real world and properly architected ASP.NET MVC applications both ViewData and ViewBag have no place. Those two are my worst enemies in ASP.NET MVC application development.

Conclusion: always use view models and strongly typed views and have fun.

like image 73
Darin Dimitrov Avatar answered Sep 22 '22 17:09

Darin Dimitrov