Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 778
Pure.Krome Avatar asked Mar 29 '09 04:03

Pure.Krome


People also ask

How can add JavaScript in ASP NET MVC?

The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.

How can you include scripts in an MVC application?

Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.

Where do I put JavaScript in razor?

A JS file for the Index component is placed in the Pages folder ( Pages/Index. razor. js ) next to the Index component ( Pages/Index. razor ).


1 Answers

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

like image 127
Kamau Malone Avatar answered Oct 03 '22 22:10

Kamau Malone