0

I've got two questions - first of all, why does .net render a javascript onclick event for asp buttons when there's a custom validator on the same page, and secondly, how can I get rid of the javascript?

It works fine when javascript is turned off, so I don't know what the point of it is. Here's a mini example:

<form id="form1" runat="server">

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

    <asp:CustomValidator ID="CustomValidator1" runat="server" 
        OnServerValidate="Stuff_Validate" EnableClientScript="false">
    </asp:CustomValidator>

</form>

This will generate the following html for the button:

<input type="submit" name="Button1" value="test" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;Button1&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="Button1" />

Without the custom validator, it's:

<input type="submit" name="Button1" value="test" id="Button1" />

Any ideas?

Thanks,

Annelie

annelie
  • 2,569
  • 6
  • 25
  • 39

2 Answers2

0

The javascript is added because the custom validation is done via javascript. It is meant to be there. How do you think the validation is done? If you got rid of the javascript the validation would not work.

anothershrubery
  • 20,461
  • 14
  • 53
  • 98
  • No, the validation isn't done via javascript, it's server side only. Works fine with javascript turned off. – annelie Feb 02 '11 at 10:13
  • Sorry, didn't know that you were only doing server side validation. But it needs to be defined and there is no way to remove it. – anothershrubery Feb 02 '11 at 10:22
0

If you look at what System.Web.UI.WebControls.Button does you can see why:

In GetPostBackOptions(), if you have any validators on the page (in the current validation group), then it will generate a script for the postback.

Then in AddAttributesToRender(), if any scripts are present, they are rendered out in the onclick event.

If you need to get around this, then you are going to have to build a custom Button

djeeg
  • 6,685
  • 3
  • 25
  • 28
  • Ok cool. I would have hoped it wouldn't generate any javascript when it's not needed in any way, but I guess we're stuck with it then. It's not a huge issue, I just had a look as our front ender asked us to remove all unnecessary javascript. As long as it works with javascript turned off I'm happy. :) Thanks for the explanation! – annelie Feb 02 '11 at 10:32
  • there is a lot more javascript that is added too, validation scripts, postback functions etc. – djeeg Feb 02 '11 at 10:49