您可以尝试使用 ViewBag。
我通过添加一个名为ItemsViewBag 的属性进行了快速测试。这将从每个区域(通过添加自己的项目)和主布局中通过添加公共项目来填充。然后它将用于呈现主布局中的项目列表。
Area1\Views\Shared_Layout.cshtml
@{
ViewBag.Title = "_Layout";
Layout = "~/Views/Shared/_Layout.cshtml";
if (ViewBag.Items == null){ViewBag.Items = new List<String>();}
ViewBag.Items.Add("Area1 item");
}
<h2>Area1 Layout</h2>
@RenderBody()
Views\Shared_Layout.cshtml(部分)
@{
if (ViewBag.Items == null){ViewBag.Items = new List<String>();}
ViewBag.Items.Add("Common Item");
}
<ul>
@foreach (var item in ViewBag.Items)
{
<li>@item</li> @* List should contain two items: "Area1 Item", and "Common Item" *@
}
</ul>
我不太喜欢该代码的外观,因为它重复了很多次并传播了 ViewBag.Items 的使用。通过使用 Html 帮助器将项目添加到列表并呈现列表,它可能会更干净。例如,您可以创建以下 2 个 Html 助手:
public static class HtmlHelpers
{
public static void AddCommonListItems(this HtmlHelper helper, params string[] values)
{
if(helper.ViewContext.ViewBag.Items == null) helper.ViewContext.ViewBag.Items=new List<String>();
helper.ViewContext.ViewBag.Items.AddRange(values);
}
public static MvcHtmlString CommonList(this HtmlHelper helper)
{
if (helper.ViewContext.ViewBag.Items == null)
return new MvcHtmlString(new TagBuilder("ul").ToString());
var itemsList = new TagBuilder("ul");
foreach (var item in helper.ViewContext.ViewBag.Items)
{
var listItem = new TagBuilder("li");
listItem.SetInnerText(item);
itemsList.InnerHtml += listItem.ToString();
}
return new MvcHtmlString(itemsList.ToString());
}
}
然后您的视图会看起来更清晰,因为它们只会使用这些帮助程序并避免重复代码:
Area1\Views\Shared_Layout.cshtml(使用新的 Html 助手)
@{
ViewBag.Title = "_Layout";
Layout = "~/Views/Shared/_Layout.cshtml";
Html.AddCommonListItems("Area1 item", "Area1 item 2");
}
<h2>Area1 Layout</h2>
@RenderBody()
Views\Shared_Layout.cshtml(其中的一部分,使用新的 Html 助手)
@{Html.AddCommonListItems("Common Item");}
@Html.CommonList()