Hi all,
The tip of the day now is how to create JavaScripts and associate it to your ASP.NET pages in Runtime.
Many times we face problems regarding passing server side values to a javascript function.
Why you don`t try to create your javascript functions in runtime?
Ya, it`s possible using the RegisterClientScriptBlock function. Let`s take a look:
The sintax is:
RegisterClientScriptBlock (type, key, script, addScriptTags);
Let`s take a look on the parameters:
type - The type of the client we`ll register, in most of cases will be our own ASPX page;
key - Keyword that allow you to get your function programatically;
script - Your JavaScript source;
addScriptTags - Boolean parameter that indicates if the function will include the tags
automatically in your JavaScript function.
Wow! easy!
Let`s take a look on how it works in pratice.
Create a new ASPX page and add these controls:
<asp:TextBox ID="txtPhrase" runat="server" Text="Hello ASP.NET and JavaScript" />
<br />
<asp:Button
ID="btnExecuteScript"
runat="server"
OnClientClick="javascript:return AlertHello();"
Text="Execute JavaScript function" />
Basically we have a textbox and a button control.
In the button we have an Event on OnClientClick calling a javascript function "AlertHello()".
We will not add this JavaScript function here (.ASPX page), we`ll add it in runtime.
Go to your C# (VB too) code and let`s start to code:
protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"function AlertHello() { alert('" + txtPhrase.Text + "'); }";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", myScript, true);
}
Create a string to hold your JavaScript function and then register your function with the RegisterClientScriptBlock function.
Do you remember the parameters?
RegisterClientScriptBlock (type, key, script, addScriptTags);
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", myScript, true);
Cool..
Run your page and you`ll get a textbox and button...
Fill your textbox with some text and click the button..
You`ll be alerted by a javascript.
It`s cool, ìt`s simple... it`s .NET
Making things easy!
have a good one!

0 comments:
Post a Comment