Ozkan
Ozkan

Reputation: 2041

serverside onclick but prevent postback in some case

I have following serverside onclick method:

protected void btnSearch_Click(object sender, EventArgs e)
{
    if (txtSearch.Text == "" || txtSearch.Text.Length < 4) {
        //NO POSTBACK HERE
    } else {
        Response.Redirect(www.google.be);
    }
}

So any advice here? I can't do it the clientside way, because I need to give a server side parameter within the url.

Thanks for help

Upvotes: 0

Views: 4422

Answers (2)

Razvan Trifan
Razvan Trifan

Reputation: 544

why not do it client side?

 <asp:Button ID="btnSearch" OnClientClick="return validateForm();" OnClick="btnSearch_Click" Text="Send" />

and have a javascript method:

function validateForm(){
    if(document.getElementById('<%= txtSearch.ClientID %>').value == '')
        return false;
    else
        return true;
}

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44605

you cannot avoid the postback once you are already executing the server side Click event.

alternatives:

  • use a client side function to check and validate and invoke a server side click only in certain cases or return false to avoid it.
  • Use UpdatePanel method to enable partial rendering and minimize the impact of the postback. There will still be a postback and whole page lifecycle but minimal page flickering.

in yoour case I think you can simply do everything client side, the code you provided above is easy to write in JQuery.

Upvotes: 1

Related Questions