0

I have a javascript header <script type="text/javascript" src="http://example.com?Key="> This Key is in aspx.cs like string Key="123456"; How can I bind this Key value to the javascript header?

3 Answers 3

1

You can access code behind variables in aspx files:

<script type="text/javascript" src="http://example.com?Key=<%= Key %>">
Sign up to request clarification or add additional context in comments.

5 Comments

The name 'Key' does not exist in the current context
Is Key a method variable? What is its scope?
@DGibbs I would use some client side scripting
src is a 3rdparty api content source
note that Key must be public or protected and must be defined in scope of page code behind class.
0

Try this way:

1-make your script referrable by code-behind by adding an id and runat="server" attributes:

<script id="myScript" runat="server" type="text/javascript">

2-in code-behind, on page_load, add the src attribute dynamically:

this.myScript.Attributes.Add("src","http://example.com?Key=" + Key);

You're done!

Comments

0

Code behind:

public Key { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Key = "123456";
    }
}

Markup:

 <script type="text/javascript" src="http://example.com?Key=<%= Key %>">
 </script>

3 Comments

Too much code. It's enough to just render proper key from server side, as OP wants.
I see more then one js function with 3 lines of code. It's: script tag with function (7 lines); body onload handler; server-side asp:HiddenField control; 4 lines of code-behind; Two other answers is one-line solution, and it more correct, because it's no need to perform any actions on client in this particular case.
Yep, that's better. One more note: you should define Key autoproperty outside of function, and you don't need to check if ispostback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.