Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag.Title value overrides Model.Title for ASP.NET MVC Editor Template

When I set ViewBag.Title at the top of a Razor template, the Model.Title editor template text box is populated using the value of ViewBag.Title instead of the expected Model.Title value. Calling Html.EditorFor(x => Model.Title) explicitly does not produce this behaviour.

How do I prevent my editor template from showing the ViewBag.Title value without maintaining a custom editor template for my model?

Code

@{
    ViewBag.Title = "Edit Post " + Model.Title;
}

@Html.EditorFor(x => Model.Title) @* renders "My Title" text box *@
@Html.EditorFor(x => Model)       @* renders "Edit Post My Title" text box *@
like image 825
Petrus Theron Avatar asked Jan 04 '13 09:01

Petrus Theron


2 Answers

The value used by Html.EditorFor can come from three places: ModelState, ViewData and Model. By the way, ViewData and ViewBag are the same thing, two ways of interacting with the same underlying dictionary.

So, to avoid conflicts when working with forms, you can either use Model instead, or use a prefix, like ViewBag._Title.


On this case ViewBag.Title is used to share data with the layout, you can also do Page.Title without worrying about changing view data.

like image 52
Max Toro Avatar answered Sep 22 '22 05:09

Max Toro


Moving the ViewBag.Title assignment to the bottom of the page worked for me.

like image 3
of the way Avatar answered Sep 23 '22 05:09

of the way