2

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.

MayureshP
  • 2,514
  • 6
  • 31
  • 41

4 Answers4

3

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.

Kamyar
  • 18,639
  • 9
  • 97
  • 171
  • but after validation, i could able to return from Javascript depending on condition(if..else) – MayureshP Jun 11 '11 at 06:39
  • i had debugger in Javascript function. When i debug with Firefox,it doesn't go javascript,diectly comes to .cs code. When i will write 'return false;',it will not go to server-side at ll – MayureshP Jun 11 '11 at 06:43
1

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

Arian
  • 12,793
  • 66
  • 176
  • 300
  • 2
    you can't prevent post back directly using c#.javascript should prevent that.if you usning jQuery it is cross platform – Arian Jun 11 '11 at 07:17
  • 2
    See this [http://api.jquery.com/event.preventDefault/](http://api.jquery.com/event.preventDefault/) and [http://www.switchonthecode.com/tutorials/jquery-snippet-the-epreventdefault-function](http://www.switchonthecode.com/tutorials/jquery-snippet-the-epreventdefault-function) – Arian Jun 11 '11 at 07:29
0

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);");
Aristos
  • 66,005
  • 16
  • 114
  • 150
0
b1.Attribute.Add("onclick","return validateNclick(this.id);");

function validateNclick(id){
//...
if(condition){
   return true
}
else{
  return false;
}
}
Yuriy Rozhovetskiy
  • 22,270
  • 4
  • 37
  • 68