Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to interpolate my angle bracket, percent, equals <%= %> syntax in external javascript files?

Often times when mixing jQuery with asp.net I need to use asp .net angle bracket percent, <% %>, syntax within a jQuery selector.

If I would like to separate the JavaScript from markup into different files is there still a way to evaluate my JavaScript file so the angle bracket percents are interpolated before reaching the client browser?

like image 650
John Grant Avatar asked Oct 01 '08 21:10

John Grant


2 Answers

If you want to evaluate <% code blocks %> as ASP.NET code in a JavaScript file, you can just put the JavaScript in an ASPX file and reference it from a SCRIPT element.

script.js.aspx:

function hideElements()
 { <% foreach(var elementId in Request.QueryString["hide"].Split(',') { %>
   jQuery('#' + <%= elementId %>).hide('slow');
   <% } %>
 }

page.aspx:

<script src="script.js.aspx?hide=<%= GetElementsIds() %>"
        type='text/javascript'></script>

page.aspx.cs:

public string GetElementIds() 
 {
   return string.Join(",", new []{control1.ClientID, control2.ClientID});
 }
like image 108
Mark Cidade Avatar answered Sep 25 '22 19:09

Mark Cidade


No, you'll need to refactor your JavaScript to accept that information as parameters.

So, instead of

jQuery('#<%=MainPanel.ClientId%>').hide('slow');

do something like this:

function hidePanel(panelId) {
        jQuery('#' + panelId).hide('slow');
}

which you can call from your page with

hidePanel('<%=MainPanel.ClientId%>');
like image 28
bdukes Avatar answered Sep 25 '22 19:09

bdukes