Reputation: 25080
this is a post back problem (I don't want to use the client side to solve this issue , there must be a way to prevent the postBack then using the client side ) , i have a button when clicked it calls a javascript function from the code behind , but before it does this it post back the page , Question is : how can i skip the post back step and jump to the javascript part ??
<script type="text/javascript">
function hello(name) {
alert("hello world from javascript " + name)
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
code Behind :
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim Myname As String = "myName"
Dim cstype As Type = Me.GetType()
Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "hello('" & Myname & "');", True)
End Sub
Upvotes: 0
Views: 1779
Reputation: 148110
You should register this script in page_load or method before the button click event.
Button1.Attributes.Add("onclick","return hello()");
Use return before the call of hello method where you register script in code behind like this
Page.ClientScript.RegisterStartupScript(cstype, "MyKey", "return hello('" & Myname & "');", True)
Remove all statement from Button1_Click if you do not want postback. Or unbind server side click event
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
End Sub
Upvotes: 1
Reputation: 43067
Use a client side handler instead of a server side handler. Remove Button1_Click
and add your js call as an OnClientClick
attribute value.
<asp:Button ID="Button1" runat="server" Text="Button"
OnClientClick="return hello('myName');" />
Or, don't use a server control at all:
<button id="button1" onclick="return hello('myName');">Button</button>
Upvotes: 3
Reputation: 8889
I think you're looking to use the OnClientClick
event of the button:
<asp:Button ID="Button1" OnClientClick="return hello('world')" runat="server" Text="Button" />
Upvotes: 1
Reputation: 629
Why not use a HTML button rather than an ASP button
<input id="Button1" type="button" value="button" runat="server" />
And server side write something like
Button1.Attributes.Add("onclick","hello()");
Upvotes: 1