Search code examples
javascriptasp.netascxclientid

Is there a way to use "<%= someObject.ClientID %>" in an external javascript file?


Is there a way to use "<%= someObject.ClientID %>" in an external javascript file?

If I use the code

<%= someObject.ClientID %>

in a script tag inside my as(c/p)x page, it works fine. On the rendered page, the ClientID is resolved. Howvever, if I put in an external JS file and just add:

It doesn't. Is there a way to do this or am I stuck with leaving that code in the as(c/p)x file?

Side question -- what is the act of doing <%=... %> in your markup file called?


Solution

  • This is totally possible.

    In your .aspx page, create a script reference to an aspx page that contains your javascript code:

    <script src="../MyJavaScriptFile.js.aspx" type='text/javascript'></script>
    

    Then, in MyJavaScriptFile.js.aspx you can write the following:

    <%@ Page Language="C#" AutoEventWireup="false"  ContentType="text/javascript" %>
    
    <% 
        var foo = new Whatever();
        foo.ClientId = 123;
    %>
    
    // Start Javascript
    var clientId = <% HttpContext.Current.Response.Write(foo.ClientId); %>;
    

    .

    Also helpful - this technique supports querystring parameters:

     <script src="../MyJavaScriptFile.js.aspx?username=<% somevalue %>" 
           type='text/javascript'></script>
    

    Then, in MyJavaScriptFile.js.aspx, I can reference the value with

    var username = '<% Request.QueryString["username"] %>';
    

    It's not the "best practice" way to do things, but it gets the job done in a way that my caveman brain can understand without resorting to fancy workarounds.