ASP.NET MVC 3 Model Binding - ViewBag.Title clash

2019-04-30 15:24发布

问题:

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?

回答1:

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