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

前端 未结 8 1297
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 15:28

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

If I use the code

<%= someObject.ClientID %>
         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 16:31

    This is totally possible.

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

    
    

    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:

     
    

    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.

提交回复
热议问题