更新任意數據:看來我是想設置一個部分鑑於ViewBag內容,而不是一個平原觀點,MVC3使得它很容易做到這一點。我仍然感興趣的是爲什麼它不適用於部分視圖,即爲什麼viewbag與部分視圖不共享。通行證從局部視圖佈局視圖
我試圖用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 /腳本佈局燒製查看ViewData
不包括鍵 「RequiredAssets」
使用
_Layout.cshtml:
<title>@ViewBag.Title</title>
@Html.RenderAssetStyles()
PartialView.cshtml:
@{
Html.RequireAssets(Assets.Grid, Assets.FileUpload);
}
我會嘗試打破RequireAssets幫助器,然後每個MvcHtmlStrings檢查它們被調用的順序。我可以實現的唯一「複製」就是將所有內容都放在一個.cshtml文件中,在這種情況下,如果您在RenderAssetStyles/RenderAssetScripts之後調用了RequireAssets,那麼在需要它們的調用之前,您將不會設置任何資產。 – 2012-04-17 15:16:04
看來我把視圖渲染爲部分視圖,我已經更新了這個問題。 – 2012-04-20 14:33:17
http://stackoverflow.com/questions/4974027/modifying-mvc-3-viewbag-in-a-partial-view-does-not-persist-to-the-layout-cshtml可能有幫助 – 2012-04-20 21:24:19