Properly registering JavaScript and CSS in MVC 2 Editor Templates

喜欢而已 提交于 2019-12-05 07:22:41

I usually add a script placeholder in my master page that is overridden by views:

Master:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title></title>
    <asp:ContentPlaceHolder ID="Styles" runat="server" />
</head>
<body>
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />
    <script type="text/javascript" src="scriptAvailableToAllPages.js"></script>
    <asp:ContentPlaceHolder ID="Scripts" runat="server" />
</body>
</html>

View:

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

<asp:Content ID="indexScripts" ContentPlaceHolderID="Scripts" runat="server">
    <script type="text/javascript" src="specific.js"></script>
</asp:Content>

<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
    <% using (Html.BeginForm()) { %>
        <%= Html.EditorFor(x => x.Date1) %>
        <%= Html.EditorFor(x => x.Date2) %>
        <%= Html.EditorFor(x => x.Date3) %>
        <input type="submit" value="OK" />
    <% } %>
</asp:Content>

Notice how the editor template is included for three different properties of the model but the required scripts are included only once.

I Build a simple scritp Manage to handle this, unfortunately i haven't done it for CSS check out Asp.Net MVC Manager for javascript include and Css files . Unfortunately, it's not working proeprly for CSS, for javascript i simply just had them at the bottom of my master file, but CSS must be in the head tag, i haven't found a way yet to do that...

But using that I've been able to had script in a custom HtmlHelper, DatePicker which I use with a template DateTime.ascx.

The telerik web asset manager allows you to accomplish what you want and is open source.

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