MayureshP
MayureshP

Reputation: 2634

prevent postback of HtmlButton in C#

I am creating HtmlButton dynamically in .cs file. Adding it to Panel using

HtmlButton b1 = new HtmlButton();
b1.Attribute.Add("onclick","javascript:validateNclick(this.id);");
pnl.Controls.Add(b1); //pnl is Server-side <Asp:Panel>

Now how could i prevent postback of it? I had written javascript which is working in IE(No postback) but not in Mozilla Firefox (go to server-side code directly). please help out.

Upvotes: 2

Views: 3371

Answers (4)

Kamyar
Kamyar

Reputation: 18797

return false to prevent postback:

b1.Attribute.Add("onclick","javascript:validateNclick(this.id);return false;");

Update:
You can also do this:

b1.Attribute.Add("onclick","javascript:return validateNclick(this.id);");  

Then in your validateNclick function, if you want to have postback, return true, if not, return false.

Upvotes: 3

IUnknown
IUnknown

Reputation: 22478

b1.Attribute.Add("onclick","return validateNclick(this.id);");

function validateNclick(id){
//...
if(condition){
   return true
}
else{
  return false;
}
}

Upvotes: 0

Aristos
Aristos

Reputation: 66649

on the javascript function return true or false and then add the return to your onclick as I show here.

    function validateNclick(me)
    {
       if(allIsOk)
       {
         return true;
       }
       else
       {
         return false
        }
    }

and your attribute.

b1.Attribute.Add("onclick","javascript:return validateNclick(this);");

Upvotes: 0

DooDoo
DooDoo

Reputation: 13487

if you use jQuery you can use preventDefault() to do this

Upvotes: 1

Related Questions