简体   繁体   English

一个页面上的Asp.net MVC多个(相同)局部视图<script> tags inside Partial View

[英]Asp.net MVC Multiple (of the same) Partial Views on a page with <script> tags inside Partial View

Looking for an elegant way of having scripts added once on a page and that's it. 寻找一种在页面上添加脚本的优雅方法,仅此而已。
I have a partial view that requires 2 CSS files and 2 JS files. 我有一个局部视图,需要2个CSS文件和2个JS文件。 In most places, there is only need for 1 of the partial views. 在大多数地方,只需要其中一部分即可。 On a single page though, I need 3 of these same partial views, and each partial view has the 4 files, so I have 6 JS links and 6 CSS links. 不过,在单个页面上,我需要3个相同的局部视图,每个局部视图都有4个文件,因此我有6个JS链接和6个CSS链接。 Quite ugly. 很丑。

I original idea was to use jQuery to see if the tags (by id) are existant on the page yet or not. 我最初的想法是使用jQuery来查看标签(按ID)是否在页面上存在。 If they aren't, then add them in. Otherwise, do nothing. 如果不是,请添加它们。否则,什么也不做。 This was going to be an inline script like.... 这将是一个内联脚本,如...。

<script type="text/javascript" language="javascript">
     function(){
           var jQueryUICSS = $("#jQueryUICSS");
           if(!jQueryUICSS){
                document.write('link id="jQueryUICSS" href="/Content/smoothness/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" />')
           }
           ...And so on for the other 3 tags.
 };

But, I'm not sure that will work (or will the lead dev accept it):P 但是,我不确定这是否行得通(或首席开发人员会接受):P

Any other ideas? 还有其他想法吗?

David, 大卫,

I use a couple of static htmlhelpers in my code for exactly this scenario. 正是在这种情况下,我在代码中使用了几个静态htmlhelpers。 it works on the principle that the context.items collection gets populated per request and therefore if an item exists in the context.items collection then it doesn't get added twice. 它的工作原理是每个请求都会填充context.items集合,因此,如果context.items集合中存在某个项目,则不会添加两次。 anyway, enough of the scottish words of wisdOOOm, 'yill jist be waantin the coade'... 无论如何,足够多的wisdOOOm苏格兰语,“你们的小伙子还是要等” ...

for our Scripts: 对于我们的脚本:

public static MvcHtmlString Script(this HtmlHelper html, string path)
{
    var filePath = VirtualPathUtility.ToAbsolute(path);
    HttpContextBase context = html.ViewContext.HttpContext;
    // don't add the file if it's already there
    if (context.Items.Contains(filePath))
        return MvcHtmlString.Create("");

    // add the beast...
    context.Items.Add(filePath, filePath);

    return MvcHtmlString.Create(
        string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>", filePath));
}

for our cuddly css: 对于我们可爱的CSS:

// standard method - renders as defined in as(cp)x file
public static MvcHtmlString Css(this HtmlHelper html, string path)
{
    return html.Css(path, false);
}
// override - to allow javascript to put css in head
public static MvcHtmlString Css(this HtmlHelper html, 
                                string path, 
                                bool renderAsAjax)
{
    var filePath = VirtualPathUtility.ToAbsolute(path);

    HttpContextBase context = html.ViewContext.HttpContext;
    // don't add the file if it's already there
    if (context.Items.Contains(filePath))
        return null;

    // otherwise, add it to the context and put on page
    // this of course only works for items going in via the current
    // request and by this method
    context.Items.Add(filePath, filePath);

    // js and css function strings
    const string jsHead = "<script type='text/javascript'>";
    const string jsFoot = "</script>";
    const string jsFunctionStt = "$(function(){";
    const string jsFunctionEnd = "});";
    string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
    string jsBody = string.Format("$('head').prepend('{0}');", linkText);

    var sb = new StringBuilder();

    if (renderAsAjax)
    {
        // join it all up now
        sb.Append(jsHead);
        sb.AppendFormat("\r\n\t");
        sb.Append(jsFunctionStt);
        sb.AppendFormat("\r\n\t\t");
        sb.Append(jsBody);
        sb.AppendFormat("\r\n\t");
        sb.Append(jsFunctionEnd);
        sb.AppendFormat("\r\n");
        sb.Append(jsFoot);
    }
    else
    {
        sb.Append(linkText);
    }

    return MvcHtmlString.Create( sb.ToString());
}

usage in both cases: 两种情况下的用法:

<%=Html.Css("~/Content/Site.Css")%>
<%=Html.Script("~/Scripts/default.js")%>

have fun... 玩得开心...

[edit] - pay particular attn to the comment line: [edit] -特别注意评论行:

// this of course only works for items going in via the current
// request and by this method

Put them in your master. 把它们放在你的主人。 CSS and Javascript files are cached. CSS和Javascript文件被缓存。 Load once and don't worry about it. 加载一次,不必担心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM