tags:

views:

173

answers:

2

Here sample extension method for calendar rendering:

public static string Calendar(this HtmlHelper html)
{
    return "<input type='text' onclick='showCalendar(this)'/>";
}

Function showCalendar() defined in calendar.js.

Is it possible to register reference to calendar.js from an extension method?

Html.Calendar() can be called more than one time, but script should be included only once.

A: 

Nice question.. for the time being I just make another extension method from which I return the script registration (say, RegisterCalendarScriptBloc()) but it would be better to have an automatic inclusion the first time a dependency is needed.

m.bagattini
A: 

Try something like this if you are using WebForms Views (not tested):

using System.Web.UI.HtmlControls;

public static string Calendar(this HtmlHelper html, HtmlHead head)
{
    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    var url = urlHelper.Content("~/Script/calendar.js");

    //var scriptControl = new HtmlGenericControl("script");
    //scriptControl.Attributes.Add("src", url);
    //scriptControl.Attributes.Add("type", "text/javascript");

    //if(head.Controls.Contains(scriptControl))
    //{
    //    head.Controls.Add(scriptControl);
    //}

    // or

    if(!head.Controls.Cast<Control>().Any(x => (x as HtmlGenericControl) != null
        && (x as HtmlGenericControl).Attributes["src"] == url))
    {
        var scriptControl = new HtmlGenericControl("script");
        scriptControl.Attributes.Add("src", url);
        scriptControl.Attributes.Add("type", "text/javascript");

        head.Controls.Add(scriptControl);
    }

    return "<input type='text' onclick='showCalendar(this)'/>";
}

In View:

<%= Html.Calendar(Header) %>

Hope this works :)

eu-ge-ne