Search code examples
c#asp.net-mvcviewbag

Strange behaviour of ViewBag


I've just noticed some weird behaviour of inputs being working together with ViewBag.

Let's say I have a simple page with Razor syntax which looks like this:

@for (int i = 0; i < 10; i++)
{
    @Html.RadioButton("TEST_NAME", i, null)
}

None of the radiobuttons are checked by default. But when I add something like @ViewBag.TEST_NAME = 5; the radiobutton with value 5 will be checked.

So why does ViewBag works like this? What is happening behind the scenes?


Solution

  • I wouldn't exactly say that's "weird" behavior. When you use one of the Razor helpers to generate a field based off a string name, it will check a few locations for a potential value for the field: ViewBag, ViewData, Model and Request. If any of these has a key/property that matches the string name of the field, it will assume that you intended the field to have that value (i.e., if any of ViewBag.TEST_NAME, ViewData["TEST_NAME"], Model.TEST_NAME and Request["TEST_NAME"] were set to 5, then that same radio button would be checked).