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?
@{
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 *@
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.
Moving the ViewBag.Title assignment to the bottom of the page worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With