【问题标题】:Update a shared view from different controllers从不同的控制器更新共享视图
【发布时间】:2014-04-24 17:07:20
【问题描述】:

我有一个局部视图,它正在一个名为 _Layout.cshtml 的共享布局中呈现。

_Layout.cshtml

<h1>@Html.Action("Home", "TestView");</h1>

控制器:

[ChildActionOnly]
public ActionResult TestView()
{
    var model = new TestViewModel();
    model.Title = "Default Title";
    return PartialView("/Views/Shared/_TestView.cshtml", model);
}

_TestView.cshtml

@model TestMVC.Models.TestViewModel
@Model.Title

到目前为止一切正常,但我想知道是否可以从不同的动作/控制器更新模型。
示例:localhost:8888/home/index,我想显示默认标题,即“默认标题”,但在某些操作/控制器例如 localhost:8888/home/contactus
我想显示一个不同的标题前。 “联系我们表格标题”。
这可能吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc-4


    【解决方案1】:

    只需添加一个可选参数:

    [ChildActionOnly]
    public ActionResult TestView(string title = "Default Title")
    {
        var model = new TestViewModel{ Title = title };
        return PartialView("/Views/Shared/_TestView.cshtml", model);
    }
    

    然后调用它

    <h1>@Html.Action("Home", "TestView", new { title = "Custom Title" })</h1>
    

    <h1>@Html.Action("Home", "TestView")</h1> //use default title
    

    【讨论】:

      【解决方案2】:

      由于您的局部视图位于&lt;h1&gt; 标记之间,这是否意味着它只能用作文本​​的占位符?

      无论哪种方式,我都觉得有比使用部分页面更好的解决方案。

      您可以简单地使用ViewBag 来设置选定的字段,例如ViewBag.CustomHeader = "Hello";.

      然后您可以删除部分视图并引用该字段:

      <h1>@ViewBag.CustomHeader</h1>
      

      请记住,您有责任每次设置该值,或者让 _Layout 页面提供默认值以防您未设置。

      <h1>@(ViewBag.CustomHeader ?? "No title was set!")</h1>
      

      第二个选项可以通过使用 Razor 的部分来设置标题。如果您愿意,这甚至允许输入 HTML。

      将您的&lt;h1&gt;(包括标签)更改为:

      @RenderSection("CustomHeader", required : false);
      //you can set required to true if you need it.
      

      然后,在您渲染的任何 View 上,您可以添加该名称的部分,它将添加到 _Layout 页面而不是包含的 View。

      @section CustomHeader {
          <h1>Hello, again! I'm another page!</h1>
      
          <!-- You can add anything you want here -->
      }
      

      更多章节信息请见here.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-19
        • 2015-02-06
        相关资源
        最近更新 更多