How to Put Javascript into an ASP.NET MVC View

Maxim Zaslavsky picture Maxim Zaslavsky · Apr 2, 2010 · Viewed 7.6k times · Source

I'm really new to ASP.NET MVC, and I'm trying to integrate some Javascript into a website I'm making as a test of this technology.

My question is this: how can I insert Javascript code into a View?

Let's say that I start out with the default ASP.NET MVC template. In terms of Views, this creates a Master page, a "Home" View, and an "About" view. The "Home" View, called Index.aspx, looks like this:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
    <p>Welcome to this testing site!</p>
</asp:Content>

Adding a <script> tag here didn't work. Where and how should I do it?

P.S.: I have a feeling I'm missing something very basic... Thanks in advance!

Answer

tvanfosson picture tvanfosson · Apr 2, 2010

One thing you may want to consider is adding a "scripts" content place holder to your master page, that loads scripts at the end of the body. This way you load your scripts at the end of the page so that it doesn't slow down loading the DOM elements (once a script starts loading it only does one request at a time, because the code can affect the DOM). This gets a little tricky with PartialView -- if you include code in them you need to figure out a way to delay executing anything that relies on later scripts after those scripts have loaded. A compromise might be to load things like jQuery in the header and the rest of your common scripts at the end of the body.

Site.Master

   <body>

   ...
   <asp:ContentPlaceHolder runat="server" id="MainContent"></asp:ContentPlaceHolder>

   ...

   <script type="text/javascript" src="<%= Url.Content( "~/scripts/jquery-1.4.1.min.js" ) %>"></script>
   <asp:ContentPlaceHolder runat="server" id="ScriptContent"></asp:ContentPlaceHolder>
   </body>
   </html>

View

  <asp:Content runat="server" ID="mainContent" ContentPlaceHolderID="MainContent">

     ... HTML ...
  </asp:Content>

  <asp:Content runat="server" ID="scriptContent" ContentPlaceHolderID="ScriptContent">

  <script type="text/javascript">
     $(function() {
       $('.selector').click( function() {
            ...
       });
     });
  </script>

  </asp:Content>