5

There seems to be an issue with the ViewBag dynamic properties. Lets say I have:

@{
    ViewBag.Title = @Model.CourseName;
}

And then in a form on the page I have:

@Html.TextBox("Title", null, new {style="width:400px;"})

Where Title is the name of a field in a database table.

When the page first opens, text box with an id of "Title" takes the value of the ViewBag.Title dynamic property.

I am a bit hazy on the exact details of Model Binding, but this does seem to be a bug, or if not, if it is something that occurs naturally as a result of the binding process, then it would be nice to be warned of this.

The work around I found, was to rename the ViewBag property to:

@{
    ViewBag.Titulo = @Model.CourseName;
}

(Title changed to Titulo - Always good to know another language to avoid name clashes...)

And the issue went away.

However, the question is:

Is this behaviour to be expected? The bug was easy to find (took an hour to figure it out, including writing this question), but I suspect that other bugs might be more, uhmmm, recondite.

EDIT:

Rephrasing the question:

Does the Model Binder automatically bind properties it finds in the ViewBag? Even when an existing property exists in the strongly typed ViewModel I have passed to the page? Surely the ViewModel should take preference?

awrigley
  • 13,481
  • 10
  • 83
  • 129

1 Answers1

5

Html.TextBox checks ViewData/ViewBag values first, then Model. To make sure it takes Model value, you must use Html.TextBoxFor.

Lukáš Novotný
  • 9,012
  • 3
  • 38
  • 46
  • Great answer. Quick comment. Though Html.TextBoxFor will work in this case, beware ListBoxFor and DropDownListFor extension methods which still check for the value in the ViewBag before the Model. – Ben Griswold Sep 10 '12 at 19:06