admin管理员组

文章数量:1331627

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 puter to table's cell

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 puter to table's cell

Share edited Jul 5, 2012 at 10:59 user1509 1,1615 gold badges17 silver badges45 bronze badges asked Jul 5, 2012 at 9:58 Jui TestJui Test 2,40916 gold badges52 silver badges80 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

simply

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

Have you tried

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

You could change this line to:

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";
}

本文标签: How to pass value of C variable to javascriptStack Overflow