Monday, March 12, 2007

Writing Javascript from the Server Side

Most of the time we might be require javascript to be created dynamically. This is required in most of the cases when you want to show some alert or confirm messages to the user. Sometimes, it may require to generate these javascript dynamically as we might need to show / process some values which are available from the serverside to these javascript functions.

This piece of code, displays the contents of the textbox in a message box to the user.

The HTML....

<html>
<head>
</head>
<body>
<form runat="server">
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Show Alert"></asp:Button>
</form>
<script>
<asp:literal runat="server" id="ltScript"></asp:literal>
</script>
</body>
</html>




The Code...

void Button1_Click(object sender, EventArgs e)
{
Literal ltScript = (Literal) Page.FindControl("ltScript");
ltScript.Text = "alert('" + TextBox1.Text + "')";
}




See also
  1. trim method in JavaScript

Labels: