Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Model Binding - ViewBag.Title clash with input of id="Title"

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?

like image 694
awrigley Avatar asked Feb 24 '11 11:02

awrigley


1 Answers

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

like image 153
Lukáš Novotný Avatar answered Oct 20 '22 14:10

Lukáš Novotný