Wednesday, April 20, 2011

ClientScriptManager.RegisterForEventValidation with HiddenField

I am trying to use to use ClientScriptManager.RegisterForEventValidation to register a hidden field and value that I am adding with ClientScriptManager.RegisterHiddenField. I doing this during the Render event. I get no error, but ASP.NET 2.0 does not appear to be validating the field. I can change the value or delete the entire field clientside using Firefox and Firebug, and ASP.NET will not throw an error like it should.

Sample code from a custom Page class:

protected override void Render(HtmlTextWriter writer)
{
    ClientScript.RegisterHiddenField("stuff", "things");
    ClientScript.RegisterForEventValidation("stuff", "things");
    base.Render(writer);
}

The hidden field is added to the page, but ASP.NET does not validate the field or value on postback. What am I missing?

From stackoverflow
  • I understand what you are trying to do, but using the Event Validation API is not really appropriate, as it is intended for validating that postback or callback events raised by the client are correct for the target server control, eg, making sure that a click is handled by the correct button, or checking that a change event on a drop down list is not for a value that wasn't originally 'known' to the server.

    In your code, you are generating a hidden field directly to the client, so there is no control for the server to reference on a postback. Even if you used a hidden field control on the server page, you still wouldn't be able to validate the field value because the control doesn't generate postback events (there is no way for the user to interact with it, and therefore no events for the server to validate).

    The simplest solution is to use ViewState to store the value of the field, then on postback verify that the posted value of the field equals the value stored in ViewState. ViewState is encrypted by default so it's a secure place to store data that shouldn't change on the client.

0 comments:

Post a Comment