简体   繁体   中英

How to pass value of C# variable to javascript?

In button click event I am writing this code.(code behind).I know button click event

protected void button_click()
{         
    string s1 = "Computer"; 
    StringBuilder sb = new StringBuilder(); 
    sb.Append(@"<script language='javascript'>"); 
    sb.Append("document.write('<table><tbody>')";); 
   sb.Append("document.write('<tr><td>Information</td></tr>')";); 
    if(s1 == "Computer" ) 
   {
     sb.Append("<tr><td>s1</td></tr>"); 
   }
   sb.Append("document.write('</tbody></table>')";);
   sb.Append(@"</script>"); 

}

It is working but I want value of s1 not s1.I know javascript is a client side programing.I wrote this function in button click event.How can pass value of s1 that is computer to table's cell

只是

sb.Append("document.write('<tr><td>" + s1 + "</td></tr>');"); 

Have you tried

    if(s1 == "Computer" )  
   { 
     sb.Append("<tr><td>"+s1+"</td></tr>"); 
   }

您可以将此行更改为:

sb.Append("<tr><td>" + s1 + "</td></tr>");

Your code is a bit irrelevant to the question you're asking. Your error has already been fixed by previous answers. But I will try to expand the asnwer further. If you wish to pass some value from C# to JavaScript, there're different methods.

1) You could make a protected method in a codebehind file and call it from your .aspx file, like

my.aspx

<script type="text/javascript">
var x = '<%= GetMyValue() %>';
DoFooWithX(x);
</script>

my.aspx.cs

protected string GetMyValue()
{
    return "example";
}

2) If you wish to execute some JavaScript once page finishes loading, you could also do it from your codebehind like this

my.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    string myScript = string.Format("myVar = '{0}';", GetMyVarValue());
    ScriptManager.RegisterStartupScript(this, this.GetType(), "MyVarSetter", myScript, true);
}
private string GetMyVarValue()
{
    return "example";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM