Mar*_*cus 2 razor asp.net-mvc-3
从局部视图添加外部文件的最佳方法是什么?
我需要做这样的事情
部分视图中的代码:
@{
var files = new List<string>();
files.Add("some path");
files.Add("some path");
ViewBag.Files = files;
}
Run Code Online (Sandbox Code Playgroud)
在布局页面中
@foreach (var file in ViewBag.Files) {
@file
}
Run Code Online (Sandbox Code Playgroud)
这实际上并没有起作用
按照承诺
@section部分视图渲染时不能渲染它,因为在此之前你可以做到这一点:
在你的_Layout.cshtml写作
@RenderSection("scripts", false)
@Html.RenderSection("scripts")
Run Code Online (Sandbox Code Playgroud)
第一行是默认值,第二行是渲染节的全新方式,我在代码中使用了两种...
现在让我们在Partial View中添加一些代码
代替
@section scripts {
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
Run Code Online (Sandbox Code Playgroud)
替换为:
@Html.Section(
@<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>, "scripts"
)
@Html.Section(
@<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>, "scripts"
)
Run Code Online (Sandbox Code Playgroud)
我们的小助手,你刚刚放入你的Models文件夹,并在你的部分视图和布局页面中引用它
// using idea from http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates/5433722#5433722
public static class HtmlExtensions
{
public static MvcHtmlString Section(this HtmlHelper htmlHelper, Func<object, HelperResult> template, string addToSection)
{
htmlHelper.ViewContext.HttpContext.Items[String.Concat("_", addToSection, "_", Guid.NewGuid())] = template;
return MvcHtmlString.Empty;
}
public static IHtmlString RenderSection(this HtmlHelper htmlHelper, string sectionName)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith(String.Concat("_", sectionName, "_")))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return MvcHtmlString.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
要渲染CSS,您只需要使用其他部分名称,例如:
在 _Layout.cshtml
@Html.RenderSection("styles")
Run Code Online (Sandbox Code Playgroud)
在您的部分视图中
@Html.Section(
@<link rel="stylesheet" href="http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css">, "styles"
)
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
4755 次 |
| 最近记录: |