Properly registering JavaScript and CSS in MVC 2 Editor Templates

Posted by Jaxidian on Stack Overflow See other posts from Stack Overflow or by Jaxidian
Published on 2010-03-27T19:26:32Z Indexed on 2010/03/27 19:33 UTC
Read the original article Hit count: 704

How do I properly register javascript blocks in an ASP.NET MVC 2 (RTM) Editor template?

The specific scenario I'm in is that I want to use Dynarch JSCal2 DateTimePicker for my standard datetime picker, but this question is in general to any reusable javascript package. I have my template working properly now but it has my JS and CSS includes in my master page and I would rather only include these things if I actually need them:

<link rel="stylesheet" type="text/css" href="../../Content/JSCal2-1.7/jscal2.css" />
<link rel="stylesheet" type="text/css" href="../../Content/JSCal2-1.7/border-radius.css" />
<script type="text/javascript" src="../../Scripts/JSCal2-1.7/jscal2.js"></script>
<script type="text/javascript" src="../../Scripts/JSCal2-1.7/lang/en.js"></script>

So obviously I could just put these lines into my template, but then if I have a screen that has 5 DateTimePickers, then this content would be duplicated 5 times which wouldn't be ideal. Anyways, I still want my View's Template to trigger this code being put into the <head> of my page.

While it is completely unrelated to my asking this question, I thought I'd share my template on here (so far) in case it's useful in any way:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>

<%= Html.TextBoxFor(model => Model) %>
<input type="button" id="<%= ViewData.TemplateInfo.GetFullHtmlFieldId("cal-trigger") %>" value="..." />

<script type="text/javascript">
    var <%= ViewData.TemplateInfo.GetFullHtmlFieldId("cal") %> = Calendar.setup({
        trigger       : "<%= ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty) %>",
        inputField    : "<%= ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty) %>",
        onSelect      : function() { this.hide(); },
        showTime      : 12,
        selectionType : Calendar.SEL_SINGLE,
        dateFormat    : '%o/%e/%Y %l:%M %P'
    });
</script>

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about JavaScript