Заполните раздел бритвы из частичного - PullRequest
98 голосов
/ 18 марта 2011

Моя основная мотивация для попытки сделать это состоит в том, чтобы получить 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>

Вот примерпросмотреть с помощью этого макета.

<h2>This is the view</h2>

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

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

А вот часть, отображаемая из представления.

<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>
}

В этом примере указанная в представлении разметка помещается в раздел, но разметка из частичнойне является.Можно ли заполнить раздел с частичным видом с помощью Razor?Если нет, то каковы другие способы получения Javascript, которые нужны только частям внизу страницы, не включая его глобально?

Ответы [ 12 ]

0 голосов
/ 27 сентября 2013

Используйте @using(Html.Delayed()){ ...your content... } расширения из ответа https://stackoverflow.com/a/18790222/1037948, чтобы визуализировать любой контент (сценарии или просто HTML) позже на странице. Внутренний Queue должен обеспечить правильный порядок.

0 голосов
/ 04 июля 2013

Основываясь на ответе мистера Белла и Шимми выше, я добавляю дополнительную функцию для сценария Bundle.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;
namespace ABC.Utility
{
public static  class PartialViewHelper
{
    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 string RequireBundleStyles(this HtmlHelper html, string bundleName)
    {
        var a = System.Web.Optimization.Styles.Render(bundleName);
        var requiredStyles = HttpContext.Current.Items["RequiredStyles"] as IHtmlString;
        if (requiredStyles == null) HttpContext.Current.Items["RequiredStyles"] = requiredStyles = a;
        return null;
    }

    public static string RequireBundleScripts(this HtmlHelper html, string bundleName)
    {
        var a=System.Web.Optimization.Scripts.Render(bundleName);
        var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as IHtmlString;
        if (requiredScripts == null) HttpContext.Current.Items["RequiredScripts"] = requiredScripts = a;
        return null;
    }

    public static HtmlString EmitRequiredBundleStyles(this HtmlHelper html)
    {
        var requiredStyles = HttpContext.Current.Items["RequiredStyles"] as IHtmlString;
        if (requiredStyles == null) return null;
        return MvcHtmlString.Create(requiredStyles.ToHtmlString()) ;
    }

    public static HtmlString EmitRequiredBundleScripts(this HtmlHelper html)
    {
        var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as IHtmlString;
        if (requiredScripts == null) return null;
        return MvcHtmlString.Create(requiredScripts.ToHtmlString());
    }

    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; }
    }
}//end class
}// end namespace  

Пример на PartialView: - @ Html.RequireBundleStyles ( "~ / пучки / FileUpload / самозагрузки / BasicPlusUI / CSS"); @ Html.RequireBundleScripts ( "~ / пучки / FileUpload / самозагрузки / BasicPlusUI / JS");

Образец на MasterPage: - @ Html.EmitRequiredBundleStyles ()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...