How do I add JavaScript to an ASP.NET MVC View?

30,669

Solution 1

One way is put a content placeholder at the bottom of your master page, then the specific slave page that needs the javascript can specify the placeholders contents as the required javascript. Other pages that don't need the javascript simply don't specify any content for the placeholder.

Solution 2

In ASP.NET MVC3, you can now use a RenderSection to achieve this, at least for simpler scenarios. Just add a RenderSection to the bottom of the layout page, and from your view fill in the appliation code

RenderSections: http://www.dotnetcurry.com/ShowArticle.aspx?ID=636

Solution 3

Your MasterPage should have a ContentPlaceHolder for the head.

<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server" />
</head>

Then you're able to include head elements (JavaScripts, StyleSheets, etc...) in your views:

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="/Scripts/jquery/ui/ui.datepicker.js" type="text/javascript">
    </script>
    <link href="/Styles/myStyle.css" rel="stylesheet" type="text/css" />
</asp:Content>
Share:
30,669
Pure.Krome
Author by

Pure.Krome

Just another djork trying to ply his art in this mad mad world. Tech stack I prefer to use: Laguage: C# / .NET Core / ASP.NET Core Editors: Visual Studio / VS Code Persistence: RavenDB, SqlServer (MSSql or Postgres) Source control: Github Containers: Docker &amp; trying to learn K&amp;'s Cloud Platform: Azure Caching/CDN: Cloudflare Finally: A Tauntaun sleeping bag is what i've always wanted spaces &gt; tabs

Updated on July 18, 2020

Comments

  • Pure.Krome
    Pure.Krome almost 4 years

    I have a simple View and I wish to add a JQuery DatePicker JavaScript to this view (and not every view, via a masterpage).

    I'm not sure what is the best way to do this.

    Second, I'm conscious of where/when my JavaScript loads. I'm a fan of YSlow and it recommends that I add any scripts to the bottom of the page, which I do.

    So, how could I do both?

    Here's the view:

    <%@ Page
        Language="C#" 
        MasterPageFile="~/Views/Shared/Site.Master" 
        Inherits="System.Web.Mvc.ViewPage" %>
    
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    
        <h2>Index</h2>
    
        <% using (Html.BeginForm()) {%>
    
        <p>
            <label for="StartDate">Start Date:</label>
            <!-- JQuery DatePicker to be added, here. -->
        </p>
        <% } %>
    </asp:Content>