Sample usage of ClientScriptManager.RegisterFo­rEventValidation

Last post 10-13-2009 6:45 PM by kgabrys. 10 replies.

Sort Posts:

  • Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    12-12-2005, 1:59 PM
    • Member
      40 point Member
    • n33470
    • Member since 12-12-2005, 5:19 PM
    • Posts 8

    Hi all,

    I have a dropDownList on a web page that is populated by client-side
    script.  I get an error on PostBack of the page.  I've seen quite a few
    posts about this, so I understand the issue, and why it's occurring.  I
    know that I need to remove the automatic event validation that ASP.NET
    is performing on the control.    One of my options is to use the page
    directive enableEventValidation="false".   I'd rather not do this for
    the entire page, I'd rather remove the event validation for only the
    dropdownlist.

    I've read that ClientScriptManager.RegisterForEventValidation can be
    used for this.   However, I haven't been able to figure out exactly how
    to do it.   I have overloaded the Render() method like this (the
    object cboLookup is the DropDownList):

            protected override void Render(System.Web.UI.HtmlTextWriter
    writer)
            {
                base.Render(writer);

    this.Page.ClientScript.RegisterForEventValidation(cboLookup.ID);

            }

    However, after doing this I still have the problem when the page is
    posted back.    I think I'm missing an extra step here, but I can't
    figure out what it is.   The method name is called
    "RegisterForEventValidation", however I actually want to un-register
    the control from ASP.NET event validation.  How do you do this?

    Can someone provide a simple example of how to bypass the automatic
    event validation code on postback of the page for a single control.

    --steve

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    12-15-2005, 5:31 PM
    • Participant
      1,536 point Participant
    • ClayCo
    • Member since 06-14-2002, 10:11 AM
    • United States
    • Posts 291
    • AspNetTeam

    Hello steve,

    The trick to getting this to work is that you need to pass the values that are admissible for the control in the call to RegisterForEventValidation.  Here's an example I got to work in my office:

    <%@ Page EnableEventValidation="true" Language="VB"  %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <script runat="server">
            Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
                ClientScript.RegisterForEventValidation("DropDownList1", "Canada")
                ClientScript.RegisterForEventValidation("DropDownList1", "Mexico")
                ClientScript.RegisterForEventValidation("DropDownList1", "United States")
                MyBase.Render(writer)
            End Sub
        </script>
        <script type="text/javascript">
            function InitializeDDL()
            {
                var oOption = document.createElement("OPTION");
                document.all("DropDownList1").options.add(oOption);
                oOption.innerText = "Canada";           
                oOption = document.createElement("OPTION");           
                document.all("DropDownList1").options.add(oOption);
                oOption.innerText = "Mexico";
                oOption = document.createElement("OPTION");               
                document.all("DropDownList1").options.add(oOption);
                oOption.innerText = "United States";
            }
        </script>
    </head>
    <body onload="InitializeDDL();">
        <form id="form1" runat="server">
        <div>
            <asp:DropDownList ID="DropDownList1" runat="server">
            </asp:DropDownList>
            <asp:Button ID="Button1" runat="server" Text="Button" />
        </div>
        </form>
    </body>
    </html>

    HTH,
    Clay

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    12-16-2005, 10:53 AM
    • Member
      40 point Member
    • n33470
    • Member since 12-12-2005, 5:19 PM
    • Posts 8

    Clay,

     

    OK, that's a good start, at least I understand more about how the RegisterForEventValidation works.  The difference with my design is that the DDL is populated by the *user* through script.   My aspx page has a DDL.   That DDL may have extra values programmatically added to it from javascript so that on postback the selected item in the DDL was not in the *original* viewstate of the DDL.

     

    I realize that this is exactly what the event validation design was supposed to flag, in this case the event validation design should flag the injected item in the DDL.    

     

    What I'm asking is how to remove the event validation check for *only* the DDL, rather than adding the @Page directive EnableEventValidtion="false".  I don't want to remove the event validation check for the whole page, I just want to remove it for only the control.   If it's possible in ASP.NET, I could provide my own routine to use for validation of the DDL on postback, as long as my routine would be a replacement for the standard ASP.NET event validation.   Is this possible?  If so, how do you do it?

     

    Does this make sense?  I've seen  a lot of forum appends asking about this problem, but no solutions posted to fix it, other than the use of the @Page directive (or the web.config setting to remove event validation for the entire site, which is out of the question).

     

    --steve

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    12-16-2005, 1:50 PM
    • Participant
      1,536 point Participant
    • ClayCo
    • Member since 06-14-2002, 10:11 AM
    • United States
    • Posts 291
    • AspNetTeam

    Hello steve,

    An easy, if somewhat Solomonic, solution to your problem is to replace your DropDownList control with something that isn't derived from WebControl at all (like, say, an HtmlSelect control).  Here's an example that I was able to run on my system:

    <%@ Page EnableEventValidation="true" Language="VB"  %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
        <title>Untitled Page</title>
        <script runat="server">
        </script>
        <script type="text/javascript">
            function InitializeDDL()
            {
                var oOption = document.createElement("OPTION");
                document.all("DropDownList1").options.add(oOption);
                oOption.innerText = "Canada";        
                oOption = document.createElement("OPTION");           
                document.all("DropDownList1").options.add(oOption);
                oOption.innerText = "Mexico";
                oOption = document.createElement("OPTION");               
                document.all("DropDownList1").options.add(oOption);
                oOption.innerText = "United States"; 
            }
        </script>
    </head>
    <body onload="InitializeDDL();">
        <form id="form1" runat="server">
        <div>
            <select size="0" ID="DropDownList1" runat="server">
            </select>
            <asp:Button ID="Button1" runat="server" Text="Button" />
            <div id="Result"></div>
            <div id="Context"></div>
        </div>
        </form>
    </body>
    </html>

    HTH,
    Clay

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    12-16-2005, 2:35 PM
    • Member
      40 point Member
    • n33470
    • Member since 12-12-2005, 5:19 PM
    • Posts 8

    Clay,

    Hmmmm, in this case, that might work.   The DDL in question resides in a user control that I might be able to redesign so that it's not rendered with a server control, rather use a straight html control.   However, I hope you'd agree with me that this is just a workaround for the real issue.

    I'd still like to understand the following:

    1. Is is possible to disable postback event validation for a single control on a page?

    2.  Is it possible to register a custom delegate to perform the event validation for a control during postback? 

    Thanks for your suggestion!

    --steve

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    12-16-2005, 3:08 PM
    • Participant
      1,536 point Participant
    • ClayCo
    • Member since 06-14-2002, 10:11 AM
    • United States
    • Posts 291
    • AspNetTeam

    Hello steve,

    At the risk of pointing out the obvious, the HtmlSelect control in the System.Web.UI.HtmlControls namespace -- as used in the previous example -- is a server control.  However, returning to the DropDownList control for a minute, there isn't a way to disable event validation entirely for that control over all possible permutations of client input.

    HTH,
    Clay  

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    04-03-2007, 12:14 AM
    • Member
      4 point Member
    • ibanezplayer
    • Member since 02-17-2007, 4:54 AM
    • Posts 3

    I was using the ATLAS cascading comboboxes on a page. I wired them up to services to do AJAX calls to populate the boxes correctly. I was so proud. Then I tried to submit the page. It blew up on me with the following error:

    Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

    I did some research. I found that the error was happening because the page did not know what valid values should be coming from the comboboxes because they were populated on the client at runtime. Being that I had the luxury of knowing what these values would be because they were coming from my own database, I figured I can do that...

    First, I needed to override the Render method to add the values alowed to the list. I did this inside the page itself (.aspx file)...

    <script runat="server">
      Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
       
    Me.RegisterValuesForCombos()
       
    MyBase.Render(writer)
      End Sub
    </script>

    I also put a SQLDataSource object on the page for each of my comboboxes...

    <asp:SqlDataSource ID="DataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>" SelectCommand="pc_list1" SelectCommandType="StoredProcedure />
    <asp:SqlDataSource ID="DataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>" SelectCommand="pc_list2" SelectCommandType="StoredProcedure" />

    I linked them to the comboxes...

    <

    asp:DropDownList ID="List1" runat="server" DataSourceID="DataSource1" DataTextField="Desc1" DataValueField="ID1" />
    <asp:DropDownList ID="List2" runat="server" DataSourceID="DataSource2" DataTextField="Desc2" DataValueField="ID2" />

    Then, I put the "magic" code behind the method RegisterValuesForCombos inside the codebehind page (.aspx.vb)

    Protected Sub RegisterValuesForCombos()
     
    Me.List1.DataBind()
     
    Me.List2.DataBind()
    End Sub

    Results... It worked. This is because at render time, the dropdowns are bound to the datasource and the page knows what valid values are.

    Enjoy!

    Stacey Brown
    ibanezowner@yahoo.com

     

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    05-01-2007, 1:06 PM
    • Member
      28 point Member
    • wander.mahet
    • Member since 03-31-2007, 3:42 AM
    • Rio de Janeiro
    • Posts 18

    In my case I'm using AJAX ASP.NET to fill with javascript a DropDownList with several values.

    I was getting that wierd error everytime my form is submitted / postedback. It seems RegisterForEventValidation doesn't work very well at all.

    I think it would be better to create a HiddenField - > to use javascript to store the DropDownList value in this hidden field. So we shall not have any problems with post back when a list control value is filled by javascript.


    Wander Mahet
    Rio de Janeiro, Brazil
  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    03-20-2008, 10:29 AM
    • Member
      6 point Member
    • mmichtch
    • Member since 03-19-2007, 5:42 PM
    • BC, Canada
    • Posts 5

    Hi Clay,

    Im my case I'm using cascading drop down lists (AJAX Control toolkit) which are populated with the service.

    If i would not touch them on the page everything works fine, but if i do any other control will throw me an Event Validation exception on postback.

    My question is rather conceptual one: it possible to EnableEventValidation="true" with AJAX Control Toolkit? when we are using sophisticated AJAX controls on the page they will obviously modify this page between posts and i do not see any options to overcome this. in the demo videos and samples about AJAX and AJAX control tolkit presenters always turn event validation off (false). Is this a recommended practice when using advanced AJAX on the page or there is a propper way to deal with it and still have event validation on?

    Thank you,

    Maxim

     

      

     

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    08-05-2009, 8:48 AM
    • Member
      2 point Member
    • DonVinchenzo
    • Member since 08-05-2009, 12:42 PM
    • Posts 1

    Not sure if you guys solved this.

    I had the error message because my dropdown was losing its place. This was because I had view state switched off at the screen and control level. I could select any value in the drop down list apart from the first entry. Selecting this first entry caused the error above.

    The issue is described well here, http://stackoverflow.com/questions/474367/dropdownlist-onselectedindexchange-to-0th-index-w-out-viewstate

    Bascially, my page was reloading every time on postback (as expected) and thinking the first (default) option was the last one selected. If I selected the first selection in the drop down, it posted back okay, but did not process the IndexChanged event because as far as it was concerned nothing had changed. ViewState (spit) gets round this by comparing the last value selected (held in viewstate) with the new one posted back....sorted salmon....the selected index gets fired...

  • Re: Sample usage of ClientScriptManager.RegisterFo­rEventValidation

    10-13-2009, 6:45 PM
    • Member
      2 point Member
    • kgabrys
    • Member since 07-12-2007, 2:47 PM
    • Posts 1

    I too have had issues with the new validation, and was hoping to use the RegisterForEventValidation.

    I am using a datalist control and as I sadly found out, the name of the clickable control is set at run time. Additionally, it is populated based on  parameters provided in a querystring. I did not see away to dynamically add parameters to the asp:SqlDataSource to use the solution suggested here. The datalist has a template of imagebutton and labels of which I am allowing users to remove values from the list when they click the image.

    While the register event idea has merit and protects the site from injection, it is not as easy to implement as one would suspect. I tried using the page level method to avoid the validation, but then the code does not seem to work right when I do that either.


    Any thoughts for these template datalist controls?

Page 1 of 1 (11 items)