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

3

17

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 *@
Julide answered 4/1, 2013 at 9:40 Comment(0)
G
7

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.

Germicide answered 17/1, 2013 at 2:3 Comment(1)
Brilliant! Page.TitlePetta
E
3

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

Ellenaellender answered 30/4, 2015 at 16:46 Comment(0)
T
2

The easy way to avoid this is just to not use ViewBag.

ViewBag is a dynamic object and it does take precedence. But you can stuff almost anything in there and it becomes difficult to debug.

Bottom line: If you need to display something dynamic such as a title, put it in your Model.

Tiffanietiffanle answered 4/1, 2013 at 9:50 Comment(2)
I use ViewBag.Title for the HTML <title> meta value displayed in my master layout template. Would ViewData["Title"] avoid the problem?Julide
I ended up just using ViewBag.PageTitle instead of ViewBag.Title to solve this.Julide

© 2022 - 2024 — McMap. All rights reserved.