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
You can access code behind variables in aspx files:
<script type="text/javascript" src="http://example.com?Key=<%= Key %>">
5 Comments
Sandy
The name 'Key' does not exist in the current contextrajeemcariazo
Is Key a method variable? What is its scope?
rajeemcariazo
@DGibbs I would use some client side scripting
Sandy
src is a 3rdparty api content sourceTommi
note that
Key must be public or protected and must be defined in scope of page code behind class.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
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
Tommi
Too much code. It's enough to just render proper key from server side, as OP wants.
Tommi
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.Tommi
Yep, that's better. One more note: you should define
Key autoproperty outside of function, and you don't need to check if ispostback.