Including script link from the HtmlHelper extension method

Here is an example extension method for a calendar:

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

The showCalendar () function is defined in calendar.js.

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

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

+2
source share
3 answers

Short answer: YES.

Here comes But ...

But you need to change the return type. if you just return the string, it will be encoded, so the browser will not actually run the script block.

In Chrome you will get something like this "", pay attention to the quotes. to get around this using IHtmlString as the return type and make a double faithful .Raw helper.

 public static IHtmlString RegisterScripts(this HtmlHelper helper) { return helper.Raw("<script>function () { DO SOMETHING }</script>"); } 
+1
source

Good question .. for now I just create another extension method from which I am returning the registration script (say RegisterCalendarScriptBloc ()), but it would be better to have automatic inclusion when necessary.

0
source

Try something like this if you are using WebForms views ( not verified ):

 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 :)

0
source

Source: https://habr.com/ru/post/1344266/


All Articles