John Smith
John Smith

Reputation: 5

How to prevent PostBack without using JavaScript?

I have an asp button in default.aspx:

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

And there is a procedure in default.aspx.vb:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Panel1.Controls.Add(New LiteralControl(Date.Now))
End Sub

And teacher asked me, how to make exactly same operation (when click on button, shows up a date) but without postback and without javascript code. I could make a java code there and use OnClientClick="return false" but it seems not right

Upvotes: 0

Views: 1520

Answers (1)

Murali Murugesan
Murali Murugesan

Reputation: 22619

Refer The Client Side of ASP.Net Pages

You can't do. The default behaviour of Button(input type=submit) is to submit/post the form to the url specified in the form's action attribute.

If you want to prevent default behaviour you need to write a javascript return false

<asp:Button ID="btn" OnClientClick="return false" runat="server" Text="Button" />

By Default asp.net post the form to the same page itself. We say this as PostBack. See the form tags action value from rendered html in browser , it will be the same page name

<input type =submit name ="btn" id="btn" 
  onclick="javascript:__doPostBack('btn','')"value ="Button">

The following built in javascript code does this

<script>
                   function __doPostBack(eventTarget, eventArgument) {
                       document.Form1.__EVENTTARGET.value = eventTarget;
                       document.Form1.__EVENTARGUMENT.value = eventArgument;
                       document.Form1.submit();
                   }
</script>

Your page will have the below fields added automatically, inorder to detect which event needs to be fired in server side. you can access simply in a request parameters like Request.Params["__EVENTTARGET"]

<input type =hidden name ="__EVENTTARGET" value ="">
<input type =hidden name ="__EVENTARGUMENT" value ="">

Upvotes: 2

Related Questions