44

This is the code which I have in my partial view

@model Contoso.MvcApplication.Models.Exercises.AbsoluteArithmetic

@using(Html.BeginForm())
{
<div>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number1</span>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">+</span>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">@Model.Number2</span>
    <span style="width: 110px; float:left; text-align:center; font-size:2.5em;">=</span>
    <span>
            @Html.EditorFor(model => model.Result)
            @Html.ValidationMessageFor(model => model.Result)
    </span>
</div>
}

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

Please note at the bottom of my code, I've got a @section, and I realized that it's not running if I set a breakpoint there. If I move that line in the _Layout.cshtml it works well, but that's not the idea.

How can I tell to MVC4 in a partial razor view that I want to add that library?

Darf Zon
  • 6,268
  • 20
  • 90
  • 149
  • 1
    We can not add scripts to a partial view. But adding scripts to the view will solve your issue. Check my answer for http://stackoverflow.com/questions/12430005/use-sections-in-partial-views-in-mvc-4-0. We can add scripts related to the partial view in to the container view dynamically. Hope that will solve your problem – Nuwan Aug 25 '13 at 12:04
  • I know the question is about MVC4, but you might be able to do this now in MVC5; see http://stackoverflow.com/questions/21827009/adding-to-script-bundle-from-partial-view-in-net-mvc-5 – CrazyPyro Aug 13 '14 at 23:31

9 Answers9

18

You can use @Scripts.Render("~/Scripts/my-script.js") for .js files and @Styles.Render("~/Content/my-Stylesheet.css") for css files.

Nb: it works for a particular bundle also More details - 'http://www.asp.net/mvc/overview/performance/bundling-and-minification'

it works on any sub-pages in razor including partial views. for more info google for the usage of these helpers

Glen Little
  • 6,951
  • 4
  • 46
  • 68
Nishanth Shaan
  • 1,422
  • 15
  • 18
  • 5
    This works, but if the scripts you include in this way are dependent on other scripts (e.g. jQuery, Bootstrap) which are included in a `@section` of the parent page they may not work if they are rendered before their dependencies. – Philip Stratford May 30 '17 at 10:30
  • I just responded to the question precisely. Generally, The scripts in the parent pages loads before the scripts in child pages. Anyway one has to make sure that the dependencies are loaded before. @PhilipStratford Do you have a proposition, I mean, in the form of code, to resolve the concern that you raise? – Nishanth Shaan Apr 18 '19 at 08:53
16

You can add the script directly at the end of the partial view html, without script section (because script section is not rendered in partial views)

<script language="javascript">
   // Your scripts here
   // ....
</script>
Pila 77
  • 395
  • 4
  • 12
9

You can't render layout sections from a partial. Move the section definition to the parent page or layout.

viperguynaz
  • 12,044
  • 4
  • 30
  • 41
  • 12
    But what's the situation when partial view is called via ajax call and it has to contain some particular js library and styles? – krypru Mar 24 '17 at 13:36
5

Check out my answer How to render a Section in a Partial View, which allows you to define Scripts and Styles in any view/partial view. It also takes care of duplicate includes.

My personal take is that sections aren't a good solution for styles and javascript includes.

Community
  • 1
  • 1
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
5

There is no common solution for this issue but you can do the following simplest ways:

1) You can create a set of extension method as the following:

https://stackoverflow.com/a/6671766/5208058

2) Simply move your javascript codes into a separated partial view and on your main view, render 2 partial views. One for the main partial view and the other for your scripts as the following:

{
    // markup and razor code for Main View here

    @Html.Partial("Main_PartialView")
}

@section Scripts
{
    @Html.Partial("JavaScript_PartialView")
}

Hope it helps.

Community
  • 1
  • 1
Varan Sinayee
  • 1,105
  • 2
  • 12
  • 26
3

This worked for me allowing me to colocate JavaScript and HTML for partial view in same file for ease of readability

In View which uses Partial View called "_MyPartialView.cshtml"

<div>
    @Html.Partial("_MyPartialView",< model for partial view>,
            new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>

@section scripts{

    @Html.Partial("_MyPartialView",<model for partial view>, 
                  new ViewDataDictionary { { "Region", "ScriptSection" } })

 }

In Partial View file

@model SomeType

@{
    var region = ViewData["Region"] as string;
}

@if (region == "HTMLSection")
{


}

@if (region == "ScriptSection")
{
        <script type="text/javascript">
    </script">
}
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
purvin
  • 61
  • 2
0

This Stackoverflow page provided a full solution to this question: Using sections in Editor/Display templates

TL;DR: Just add the Forloop.HtmlHelpers nuget package https://www.nuget.org/packages/Forloop.HtmlHelpers/ to your project to allow you to run Javascript from Razor Partial Views and Templates in ASP.NET MVC. I have personally used this with my MVC 5 project.

Community
  • 1
  • 1
0

If you want to include specific scripts only in some partial views and avoid spreading them unnecessarily throughout your application, you can do something like this:

Define a bundle pointing to an empty javascript file in your BundleConfig.cs:

 bundles.Add(new ScriptBundle("~/bundles/empty").Include(
                    "~/Scripts/empty.js"
            ));

In the head section of your _Layout.cshtml, add this variable:

@{
        ViewBag.AdditionalBundle = String.IsNullOrEmpty(ViewBag.AdditionalBundle) ? "~/bundles/empty" : ViewBag.AdditionalBundle;
    }

In the bottom of your _Layout.cshtml, render any additional bundles you want:

@Scripts.Render("~/bundles/lib")
    @Scripts.Render(@ViewBag.AdditionalBundle);
    @RenderSection("scripts", required: false)

And finally, in the partial view in which you need any specific scripts, just add the corresponding bundle to the variable:

ViewBag.AdditionalBundle = "~/bundles/mySpecificBundle";

Partial views are rendered before the _Layout.cshtml, so you need that verification at the top of the file. It goes like this: if any partial view assigned a value to ViewBag.AdditionalBundle, then use it. Otherwise, render an empty script.

Glauber
  • 25
  • 7
0

Noob trick: Define a function in an already loaded file, and call the function on partial view load.

1.Have a separate js file that you load with your usual bundle:

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/CustomScripts").Include(
    "~/Scripts/Custom/partial-view.js"
));
  1. Load the custom script bundle like any other bundle in your layout

_Layout.cshtml

@Scripts.Render("~/bundles/CustomScripts");
  1. define a function, in our case OnPartialViewLoad function in the custom js file:

partial-view.js

function OnPartialViewLoad() {
    // ... your onLoad work
}
  1. add a document.ready() function to the end of your partial view and call the onLoaded function.

partialView.cshtml

<script type="text/javascript">
    $(document).ready(function(){
        OnPartialViewLoad();
    });
</script>
Yashash Gaurav
  • 581
  • 5
  • 9