Call java script function through Code behind (.cs) in C#

Hi friends
        Here is the code to call a java script function from the .cs page of the asp.net application.
lets take aspx page and drag a button on it.

the source code should be like this ,

<asp:Button ID="btnAction" runat="server" onclick="btnAction_Click" Text="Action" />


Now come to the .cs file ,


 protected void btnAction_Click(object sender, EventArgs e)
    {
        string myscript = "alert ('Rajesh C# Blog 4 U');";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", myscript, true);
    }



Registers the client script with the Page object using a type, key, and script literal.

Namespace:  System.Web.UI
Assembly:  System.Web (in System.Web.dll)

Parameters

type
Type: System::Type The type of the client script to register. 
key
Type: System::String The key of the client script to register. 
script
Type: System::String The client script literal to register. 
Hope this will helps you 
Regards,
Rajesh

2 comments:

  1. how to use this in master.cs file will you tell me please

    ReplyDelete
  2. hey Durgesh,
    You can use this code on Master.cs as well .. by the same way . just take an example you paste this code on Master.cs page load .
    string myscript = "alert ('Rajesh C# Blog 4 U');";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", myscript, true);
    this will work
    thks

    ReplyDelete