Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine an ASP.Net MVC Bundle is rendered before or not?

Here is the situation :

On a MVC application I have a partial that is rendering a script bundle. this partial is rendered several times.

Is there a built-in way to determine an specific Bundle is rendered before in some place on page ?

Thanks professionals

Update : here is the code for clearing the condition

main layout :

<html>
  <body>
    @if(someCondition){
      @Html.RenderPartial("SamePartial")
      @Html.RenderPartial("SamePartial")
      @Html.RenderPartial("SamePartial")
    }
  </body>
</html>

and this is inside partial :

<div>Blah Blah Blah</div>

@Scripts.Render("~/bundles/JusNeededInsidePartial")
@Styles.Render("~/Themes/styles/JusNeededInsidePartial")

partial is rendered several times. I need a way to render bundles 1 time only

like image 692
abzarak Avatar asked Nov 01 '25 01:11

abzarak


2 Answers

Define a Razor section:

@section MySpecialScripts {
    @Scripts.Render("~/bundles/MySpecialScriptsBundle")
}

in views where you need such scripts and add the following to the main layout:

@if (IsSectionDefined("MySpecialScripts")) {
    RenderSection("MySpecialScripts")
}
like image 132
Marcin Wachulski Avatar answered Nov 04 '25 03:11

Marcin Wachulski


I'd be a bit leery about putting bundles inside your partial views like you are doing.

For best performance, I'd suggest putting scripts at the bottom of your page (ref: http://developer.yahoo.com/blogs/ydn/high-performance-sites-rule-6-move-scripts-bottom-7200.html)

If your bundles contain stylesheets, you're going to be putting them in the body, which is still valid, but I like to organize them so that they're all together.

Typically what I would do is add this to my _Layout.cshtml right before the closing </head> tag:

 @RenderSection("Head", required: false)

Then, in my View, I could have:

@Html.RenderPartial("SamePartial")
@Html.RenderPartial("SamePartial")
@Html.RenderPartial("SamePartial")

@section head{
    @Scripts.Render("~/bundles/myBundle")
}

And if I wanted to do something similar on another View:

@Html.RenderPartial("OtherPartial")
@Html.RenderPartial("OtherPartial")

@section head{
    @Scripts.Render("~/bundles/myOtherBundle")
}

I know this is a bit different than what you were asking for, but I think there's value in the flexibility of this solution.

And if you're loading things dynamically, you could always put a simple condition in your section:

@section head{
    @if(SomeCondition){
        @Scripts.Render("~/bundles/modernizr")
    }
}
like image 43
Mister Epic Avatar answered Nov 04 '25 04:11

Mister Epic