Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read c# variable from javascript

Status
Not open for further replies.

GoTerps88

Programmer
Apr 30, 2007
174
US
I am dynamically generating a string in c# that I want to fill a <div> element within javascript. I'm having a few problems with the string parsing.

The 'somepage.aspx' is throwing an error within the javascript, says it is expecting ;.

Code:
<div id="stuff">
</div>
<%
string strDiv = "<ul><li><a href='somepage.aspx'></a></li></ul>";

%>
<script type="text/javascript">
var str = '<%= strDiv %>';
document.getElementById('stuff') = str;
</script>
 
document.getElementById('stuff').innerHTML = str;
 
I think the answer may involve using the Page.RegisterStartupScript method instead of what I am using now.
 
Actually I don't think you have to define a variable as public in order to use it in the script.

I ended up using the Page.RegisterStartupScript to solve the problem.


Code:
const string admin = "admin";
const string adminPg = "admin.aspx";

string myScript="<script language='javascript'>"; 

StringBuilder sb = new StringBuilder(200);
sb.Append("'<ul>");

sb.Append("<li id=" + admin + "><a href=" + adminPg + ">" + admin + "</a></li>");

sb.Append("</ul>';");
myScript += "document.getElementById('myDiv').innerHTML= " + sb.ToString();
myScript += "</script>";

Page.RegisterStartupScript("myScript", myScript);
 
I released that the Page.RegisterStartupScript is now deprecated, so I substituted the ClientScriptManager.RegisterStartupScript in place.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top