Isaac04 Isaac04 - 1 month ago 11
HTML Question

Using javascript in Asp.NET

I have a problem that I want to call the javascript code, when selection of gridview is changing. But, I can not start my javascript. How can I do that?

//Html side

<input ID="addressinput" type="text" runat="server" style="display:none;"/>

<asp:Button ID="Button1" runat="server" Text="Button" style="display:none;" OnClientClick="return myfunction();" onclick="Button1_Click" />


//Javascript

function myfunction() {
FindLocaiton();
}


//C#

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
addressinput.Value = GridView1.SelectedRow.Cells[1].Text;
Button1.Click += new EventHandler(Button1_Click);
}

protected void Button1_Click(object sender, EventArgs e)
{

}

Answer

As per following code java script function myfunction() will execute first then the server side button click event.... so u need to add following code in button click event to execute javascript code after server side code..

ClientScript.RegisterStartupScript(this.GetType(), "msg", "myfunction();")

Following is the code that i have tested and its working.

ASPX Code.

<script type="text/javascript">
    function myfunction() {

        alert('In JavaScript Code after server side code execution');
    }
</script>

   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

C# Code :-

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("In Button Click event");
        ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script language=javascript>myfunction();</script>");
    }