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

2019-03-22 20:37发布

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>

3条回答
放荡不羁爱自由
2楼-- · 2019-03-22 21:00

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

查看更多
相关推荐>>
3楼-- · 2019-03-22 21:18

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-22 21:22

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>
查看更多
登录 后发表回答