proseidon
proseidon

Reputation: 2305

Calling a button event without postback

I have a button that I want to function like normal, except I don't want it to postback.

If a user clicks it, I want to execute the Button Click event on the next postback, I just don't want that particular button to be able to postback.

I tried this:

<asp:Button ID="ChangeAllBtn" runat="server" Text="Change All" OnClientClick="return false;" OnClick="ChangeAllBtnClick" />

But it doesn't call the ChangeAllBtnClick after I postback. If I remove the "return false;", then there is postback before I want it.

What do?

Upvotes: 2

Views: 7935

Answers (3)

Seth Greenstein
Seth Greenstein

Reputation: 153

Will the following work? Set the onclientclick javascript to return false so it doesn't postback, but also have that function set a value in a hidden field to "1",the default being "0" basically a flag.

On the PageLoad check the value of the hidden field, if the value is one, then execute the desired code and set the hidden field value back to 0.

<!------HTML Code------>
<input type="hidden" id="hdnChangeAllFlag  value="0" />
<asp:Button ID="ChangeAllBtn" runat="server" Text="Change All" OnClientClick="return > ChangeAllClicked()" />

<script>
function ChangeAllClicked()
{
$("#hdnChangeAllFlag").val('1');
return false;
}
</script>
''' Server Side Code

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Request("hdnChangeAllFlag")="1" and IsPostback Then
        ''''Y
    End If

End Sub

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

You can have a hidden field that stores the first click. If the user is clicking the second time you can try to make a ajax request ..

This way there will not be a postback in your page.

Upvotes: 2

Abe Miessler
Abe Miessler

Reputation: 85046

Seems like an odd request. I'm not sure how to do it off the top of my head. Would it be possible to structure your code in such a way that when you post back it just executes the code that would have been in your button click event? Example:

void ChangeAllBtnClick(object o, EventArgs e)
{
   DoStuff();
}

void RealButton_BtnClick(object o, EventArgs e)
{
   DoStuff(); //Executing all the code that would have been run for ChangeAllBtnClick here
   /*
      code for RealButton would be in here...
   */
}

void DoStuff()
{
   //Whatever
}

If that's not an option I would probably create a hidden field that is a server side control. Then you can set this from the client side script and check the value on the server side.

Upvotes: 1

Related Questions