Populating dropdownlist client side. Getting post

2019-07-18 04:51发布

问题:

I have a webcontrol with two dropdownlists on in. When you choose something from the first, the second is populated accordingly. When post back occurs I get the old:

Invalid postback or callback argument. Event validation is enabled using 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 know what this problem is; I am populating the dropdown with unexpected data. I've read up on the error and found fixes like overriding the Render method where you call "RegisterForEventValidation" for each new dropdownlist item. I can't do this, however, as I am repopulating the dropdown client side.

In theory I could use this method if I added every possible value (around 3000) that could be included in the dropdown, but I didn't really want to do this.

Are there any other ways of getting around this error, without disabling EventValidation or populating the dropdownlist server side?

回答1:

You might have to use a basic html select and look for the selected value on the Request.Form collection.

With the DropdownList I'm afraid you have no other option but those 2.



回答2:

Unfortunately, there is no support for disabling event validation on a per-control basis. In my experience, though, disabling event validation on a page is not all that bad.

Regardless of whether event validation is enabled, wise developers validate all input. Tools like the AntiXSS library can come in handy for identifying and/or sanitizing potentially malicious input.

If you are already following practices where you carefully validate form input, then disabling the out-of-the-box ASP.NET validation behavior should be a viable solution that doesn't add substantial risk to your project.



回答3:

Render method may solve your issue. But, faster is subclassing. Do nothing, but subclass your DropDownList and use that in your aspx page.

I did it, and worked.