【问题标题】:ViewBag.Title value overrides Model.Title for ASP.NET MVC Editor TemplateViewBag.Title 值覆盖 ASP.NET MVC 编辑器模板的 Model.Title
【发布时间】:2026-01-01 13:50:01
【问题描述】:

当我在 Razor 模板的顶部设置 ViewBag.Title 时,Model.Title 编辑器模板文本框将使用 ViewBag.Title 的值而不是预期的 Model.Title 值填充。显式调用 Html.EditorFor(x => Model.Title) 不会产生这种行为。

如何防止我的编辑器模板显示 ViewBag.Title 值而不为我的模型维护自定义编辑器模板?

代码

@{
    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 *@

【问题讨论】:

    标签: asp.net-mvc viewbag mvc-editor-templates editorformodel


    【解决方案1】:

    Html.EditorFor 使用的值可以来自三个地方:ModelStateViewDataModel。顺便说一句,ViewDataViewBag 是同一个东西,是与同一个底层字典交互的两种方式。

    因此,为避免在处理表单时发生冲突,您可以改用 Model,也可以使用前缀,例如 ViewBag._Title


    在这种情况下ViewBag.Title 用于与布局共享数据,您也可以使用Page.Title 而不必担心更改视图数据。

    【讨论】:

    • 太棒了! Page.Title
    【解决方案2】:

    ViewBag.Title 分配到页面底部对我有用。

    【讨论】:

      【解决方案3】:

      避免这种情况的简单方法就是不使用ViewBag

      ViewBag 是一个动态对象,它确实具有优先权。但是你几乎可以把任何东西都塞进去,而且调试起来很困难。

      底线:如果您需要显示动态内容(例如标题),请将其放入您的Model

      【讨论】:

      • 我将ViewBag.Title 用于在我的主布局模板中显示的HTML <title> 元值。 ViewData["Title"] 会避免这个问题吗?
      • 我最终只是使用ViewBag.PageTitle 而不是ViewBag.Title 来解决这个问题。