javascript - 从部分填充 Razor 部分

标签 javascript asp.net-mvc-3 razor

我尝试这样做的主要动机是让 Javascript 仅在页面底部的部分需要 Javascript 的其余部分,而不是在呈现部分的页面中间。

这是我正在尝试做的一个简化示例:

这是正文之前带有脚本部分的布局。

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />    
</head>

<body>
    @RenderBody()
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    @RenderSection("Scripts", false)
</body>
</html>

这是使用此布局的示例 View 。

<h2>This is the view</h2>

@{Html.RenderPartial("_Partial");}

@section Scripts {
<script type="text/javascript">
        alert("I'm a view.");
</script>
}

这是从 View 中呈现的部分。

<p>This is the partial.</p>

@* this never makes it into the rendered page *@
@section Scripts {
<script type="text/javascript">
    alert("I'm a partial."); 
</script>
}

在此示例中, View 中指定的标记被放置到部分中,但部分中的标记没有。是否可以使用 Razor 从局部 View 填充部分?如果不是,还有哪些其他方法可以获取仅在页面底部部分需要的 Javascript 而无需全局包含它?

最佳答案

我处理这个问题的方法是为 HtmlHelper 类编写几个扩展方法。这允许部分 View 说他们需要一个脚本,然后在写入标记的布局 View 中我调用我的辅助方法来发出所需的脚本

以下是辅助方法:

public static string RequireScript(this HtmlHelper html, string path, int priority = 1)
{
    var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List<ResourceInclude>;
    if (requiredScripts == null) HttpContext.Current.Items["RequiredScripts"] = requiredScripts = new List<ResourceInclude>();
    if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority });
    return null;
}

public static HtmlString EmitRequiredScripts(this HtmlHelper html)
{
    var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List<ResourceInclude>;
    if (requiredScripts == null) return null;
    StringBuilder sb = new StringBuilder();
    foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
    {
        sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
    }
    return new HtmlString(sb.ToString());
}
public class ResourceInclude
{
    public string Path { get; set; }
    public int Priority { get; set; }
}

一旦你有了它,你的局部 View 只需要调用 @Html.RequireScript("/Path/To/Script")

然后在布局 View 的头部调用 @Html.EmitRequiredScripts()

这样做的一个额外好处是,它允许您剔除重复的脚本请求。如果您有多个需要给定脚本的 View /部分 View ,您可以放心地假设您只会输出一次

关于javascript - 从部分填充 Razor 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5355427/

相关文章:

javascript - 如何使用javascript获得自动点击的链接

asp.net-mvc-3 - 将客户端复选框单击处理程序添加到 Razor View

asp.net-mvc-3 - 如何在 MVC3 站点上获取默认 html 页面

asp.net-mvc - 操作过滤器异常

c# - 无法理解如何在 ASP.net Core 中处理数据

javascript - 发布在 Ajax 中无法将输入保存到数据库

javascript - Angular JS 游戏 - 使用方法创建和销毁子 Controller

asp.net-mvc - 关闭并提交表单 Bootstrap 3

javascript - 表中每个控件的唯一 ID

javascript - 在 js 中检查(读取)消息到控制台