2

A very basic question: how can I easily view the contents of a ViewBag while debugging ASP.NET MVC controllers in Visual Studio?

As a workaround, I use temporary variables:

string tmp = ViewBag.MyData;

So, the problem is that viewing ViewBag.MyData directly is difficult, tmp is easy.

masa
  • 2,762
  • 3
  • 21
  • 32

5 Answers5

5

To view the contents of ViewBag when debugging:

  • At a breakpoint...
  • Open (Debug menu / QuickWatch) and type in ViewBag.
  • Click the arrows at the left-hand-side for ViewBag, then for Dynamic.
  • The contents of ViewBag will be displayed.

enter image description here

3

You can easily add ViewBag to Watcher. Then expand Dynamic View to see all properties.

enter image description here

ebattulga
  • 10,774
  • 20
  • 78
  • 116
2

I would suggest using "View Models", for example:

ViewModel

public class HomeViewModel {
    public string Text { get; set;}
}

Controller

public ActionResult Index() {
    var viewModel = new HomeViewModel {
         Text = "My Text"
    };

    return View(viewModel);
}

View

@model MyApplication.ViewModels.HomeViewModel

This is my text: @Model.Text
janhartmann
  • 14,713
  • 15
  • 82
  • 138
1

I may be missing the point here - But can you not simply put a break-point on the ViewBag property you want to view?

Click your ViewBag.MyData and hit F9. When debugging, once the break-point is hit, hover your mouse over the ViewBag to see its contents.

MalvEarp
  • 525
  • 2
  • 5
  • 19
0

You can view ViewData instead. Each key in ViewData dictionary is a same property of ViewBag

What's the difference between ViewData and ViewBag?

Community
  • 1
  • 1
hmnzr
  • 1,390
  • 1
  • 15
  • 24