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

喜欢而已 提交于 2019-12-09 07:30:36

问题


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>

回答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.




回答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




回答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>


来源:https://stackoverflow.com/questions/694111/how-do-i-add-javascript-to-an-asp-net-mvc-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!