什么是从控制器将数据传递到一个视图布局的最佳做法? [英] What is the best practice of passing data from a controller to a view layout?

查看:113
本文介绍了什么是从控制器将数据传递到一个视图布局的最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个需要对每个页面的页眉动态内容的MVC网站。

I currently have a MVC site that needs to have dynamic content on the header of every page.

我目前获得所需的数据作为普通的控制器,并将其放置在一个视图模型。在视图中,我取数据,并坚持到Viewbag模板部分,最后,主要布局页面上,我走Viewbag数据,并把它传递给控制头部分。

I currently get the required data as normal in the controller and place it in a View Model. In the view, I take the data and stick the template parts in to the Viewbag and finally, on the main layout page, I take the Viewbag data and pass it to the partial which controls the header.

我读过,我不应该尽可能使用Viewbag,与时代我通过全面的数据量只是感觉不对。

I've read that I shouldn't use Viewbag where possible, and the amount of times I pass the data round just doesn't feel right.

我能想到的,以改善这个问题的唯一方法是创建主布局的部分,然后把部分/数据视图的部分 - 但是,也有〜30页,这一次不觉得自己是正确的路线。

The only way I can think of to improve this is to create a section on the main layout, and then put the partial/data in the section of the view - however, there are ~30 pages and this again doesn't feel like the correct route.

有没有更好的方法,这样做/什么是采取有去到主视图动态数据的最佳实践?

Is there a better way to do this/what are the best practices for taking dynamic data that has to go to the main view?

推荐答案

您可以与儿童行为做到这一点。您可以重复这个动作,甚至包括它在_layout页。

You can do this with Child Actions. You can reuse this action and even include it in the _Layout page.

下面是一个孩子的行动来显示一些头信息。它被标记 ChildActionOnly ,因此只能另一种观点中调用。它也需要的OutputCache 的优势,将结果保存5分钟。

Here's a child action to display some header info. It is marked ChildActionOnly so it can only be called within another view. It also takes advantage of OutputCache to save a result for 5 minutes.

[ChildActionOnly]
[OutputCache(Duration = 5 * 60)]
public ActionResult Header(string section)
{
    var info = new HeaderInfo
    {
        Section = section,
        Today = DateTime.Now
    };
    return PartialView("_header", info);
}

_header.cshtml

@model HeaderInfo
<div>
    <span>@Model.Section</span>
    <span>@Model.Today.ToLongTimeString()</span>
</div>

然后用<一个视图或布局中使用此href=\"http://stackoverflow.com/questions/2955261/difference-between-html-renderaction-and-html-action\">Html.Action()或.RenderAction()。

@Html.Action("Header", "Home", new { section = "Cake" })
// or
@{Html.RenderAction("Header", "Home", new { section = "Pie" });}

您可以指定布局内的部分这时如果在视图present有条件地呈现。

You can specify a section inside your layout then conditionally render if present in the view.

_Layout.cshtml

@RenderSection("header", required: false)

主视图

@section header {
    @{Html.RenderAction("Header", "Home", new { section = "Cake" })}
}

这篇关于什么是从控制器将数据传递到一个视图布局的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆