CiccioMiami
CiccioMiami

Reputation: 8256

Load Javascript from a Partial View in ASP.NET MVC3

I have an ASP.NET MVC3 application in C# and Razor.

I use the standard _Layout.cshtml from the MVC3 application template in VS2010. I would like to add Javascript code in one of my Partial View just when the View is rendered and not attach the Javascript directly in the _Layout.

My View looks like this:

@model MyNameSpace.ViewModels.MyViewModel

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Filters</legend>

        @{ Html.RenderPartial("Filters", Model.Filters);  }

        <p>
            <input type="submit" value="Submit" />
        </p>

    </fieldset>
}

And my Partial View Filters.cshtml looks like this:

@model MyNameSpace.ViewModels.FiltersViewModel

<p>
@Html.DropDownListFor(
    x => x.Type, 
    new SelectList(Model.Types, "Value", "Text"),
    "-- select type --"
)
</p>

<p>
@Html.DropDownListFor(
    x => x.Category, 
    new SelectList(Model.Categories, "Value", "Text"),
    "-- select category --"
)</p>

<script type="text/javascript">
   //Some Javascript
</script>

If I leave the View like this, the Javascript is rendered inside the <body> and it looks very ugly. I can add the Javascript directly in the <head> section of the _Layout but it is not what I want. How can I achieve my purpose?

Upvotes: 1

Views: 3246

Answers (1)

Ph0en1x
Ph0en1x

Reputation: 10067

add @RenderSection("HeadContent", required: false) inside your main layout (masterpage) and then add something like

    @section HeadContent {
        <link href="@Url.Content("~/Content/styles/admin.css")" rel="stylesheet" type="text/css" />
        <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>    
    } 

in your partial view

When razor will compiling html page it will place content from @section block from the partial view to the place where you put @RenderSection("HeadContent", required: false) on the layout (masterpage). If there are no @section block on the partial view, then nothing will be added.

Upvotes: 5

Related Questions