更新:似乎我试图在局部视图中设置 ViewBag 内容,而不是在普通视图中,MVC3 使得它很容易做到这一点。我仍然感兴趣为什么它不适用于部分视图,即为什么视图包不与部分视图共享。
我正在尝试使用ViewData
/将部分视图中的一些数据传递到布局视图ViewBag
// Used in the partial view
public static void RequireAssets(this HtmlHelper helper, params Asset[] assets)
{
var alreadyRequired = helper.ViewData["RequiredAssets"] as List<Asset>;
if (alreadyRequired == null)
{
alreadyRequired = new List<Asset>();
helper.ViewData.Add("RequiredAssets", alreadyRequired);
}
foreach (var asset in assets.Where(anAsset => !alreadyRequired.Contains(anAsset)))
alreadyRequired.Add(asset);
}
// Used in the layout view
public static MvcHtmlString RenderAssetStyles(this HtmlHelper helper)
{
var requiredAssets = helper.ViewData["RequiredAssets"] as List<Asset>;
return requiredAssets == null ? null : GetStyleSheets(requiredAssets.Select(e => new StyleSheet(e)).ToArray());
}
public static MvcHtmlString RenderAssetScripts(this HtmlHelper helper)
{
var requiredAssets = helper.ViewData["RequiredAssets"] as List<Asset>;
return requiredAssets == null ? null : GetScripts(requiredAssets.Select(e => new Script(e)).ToArray());
}
问题是当在布局视图中触发 RenderAssetStyles/Scripts 时,ViewData
不包含键“RequiredAssets”
用法
_Layout.cshtml:
<title>@ViewBag.Title</title>
@Html.RenderAssetStyles()
部分视图.cshtml:
@{
Html.RequireAssets(Assets.Grid, Assets.FileUpload);
}