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?
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});
}
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%>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With