开发者

Problem with postbacks and validators

开发者 https://www.devze.com 2022-12-20 10:04 出处:网络
I\'m using the built-in ASP validators on a few form elements. They work fine - if I click the submit button (a Button), valid开发者_如何学Pythonation occurs without postback and errors are displayed

I'm using the built-in ASP validators on a few form elements. They work fine - if I click the submit button (a Button), valid开发者_如何学Pythonation occurs without postback and errors are displayed in a ValidationSummary. When that occurs, I also want to call a method in codebehind which changes the CSS of elements, switching their background color to red to reflect errors. I've tried to call this method using both OnClick and OnClientClick in the submit Button, but neither parameter seems to fire the method - client-side validation always takes priority, and a postback never occurs. Can anyone enlighten me?

EDIT #1

Using orandovs link worked alright for changing the element itself, but how about its parent?

For example, in C# I'm doing:

foreach (BaseValidator validator in Page.Validators)
{
    Panel panel = validator.Parent as Panel;

    if (!validator.IsValid)
        panel.CssClass = "error";
    else
        panel.CssClass = "normal";
}

Is there a way to get the parent control (which are all consistently Panels, so I know CssClass will exist) using JavaScript? Something like:

 $("#" + Page_Validators[i].controltovalidate.parent).CssClass("error");


If client side validation fails, there is no post back, so you have two options:

  1. Write client side javascript to do what you want to do.
  2. Set all validators to validate on the server only (Set EnableClientScript = "false") (Not recommended)

You can do an Ajax call on failed validation, but that involves client side code, so it falls under option 1.


I assume you are using the JQuery library and you are using the javascript code from this answer.

Jquery has a parent() and an addClass() function. Documentation: parent, addClass.

Here is the modified code to set the parent element's css class:

if (!Page_Validators[i].isvalid) {
   $("#" + Page_Validators[i].controltovalidate).parent().addClass("error");
}
else{
    //Make sure you remove the error class if the error has been fixed
    $("#" + Page_Validators[i].controltovalidate).parent().removeClass("error");
}


Why not modify the CssClass property of the object or write some javascript code using Response.Write()


Client-side validation will block a postback. There are a few ways to do this. If you truly wish for a postback to occur, you can put this inside of an update panel and force a partial postback, which would fire off your code behind. You could also perform the CSS changing in javascript, and keep everything client-side.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号