Why does .NET render javascript for a button when there's a custom validator on the page?

1.6k views Asked by At

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

2

There are 2 answers

2
djeeg On BEST ANSWER

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

2
anothershrubery On

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.