Pass arbitrary data from a partial view to the layout view
更新:我似乎是在一个局部视图中设置viewbag内容,而不是在一个普通视图中,MVC3使这一操作非常容易。我仍然感兴趣为什么它不适用于局部视图,也就是说,为什么视图包不能与局部视图共享。
我试图通过使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // 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()); } |
问题是,当在布局视图中激发renderassets样式/脚本时,
用法
SytLM.CsHTML:
1 2 | @ViewBag.Title @Html.RenderAssetStyles() |
部件视图.cshtml:
1 2 3 | @{ Html.RequireAssets(Assets.Grid, Assets.FileUpload); } |
我不能复制这个。我必须简化您的代码并做出一些假设。但是下面的工作对我来说很好。
第四讲
1 2 3 4 5 | @using MyProject.Helpers @ViewBag.Title @Html.RenderAssetStyles() @Html.RenderAssetScripts() @RenderBody() |
CVTML
1 2 3 4 5 6 | @using MyProject.Helpers @{ ViewBag.Title ="View"; Html.RequireAssets(Asset.Grid, Asset.FileUpload); Layout ="~/Views/Shared/_Layout.cshtml"; } |
HelpS.CS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MyProject.Helpers { public enum Asset { Grid=1, FileUpload=2 } public static class Helper { 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 : MvcHtmlString.Create("Test Style"); } public static MvcHtmlString RenderAssetScripts(this HtmlHelper helper) { var requiredAssets = helper.ViewData["RequiredAssets"] as List<Asset>; return requiredAssets == null ? null : MvcHtmlString.Create("Test Script"); } } } |
认为你做错了什么。无法复制你的努力。尝试检查-您的视图是否使用精确的此布局。一切都可以,试着创建一个简单的例子,它将是可复制的。