Home > Net >  Adding and removing "is-invalid" class from CodeBehind in ASP.NET
Adding and removing "is-invalid" class from CodeBehind in ASP.NET

Time:10-15

I'm creating an ASP site where the user has to fill out a form. Textboxes, dropdownlists, and I'm using Bootstrap 4 for the style and the whole content is in an update panel so the page feels responsive without having to do a full postback.

So when the user hits the submit button, I'm checking if any of the textboxes or dropdownlists are empty. If they are, I don't insert into the database, and I append "is-invalid" to the empty fields' CssClass.

Control.CssClass = " is-invalid";

Up to this point, it's all fine. The empty fields get red.

But then if the user fills in the empty fields and click on the submit again, the fields remain red, even though I replace the "is-invalid" with nothing.

Control.CssClass.Replace(" is-invalid", "");

So my question is, why doesn't the red disappear? If changing the CssClass works from the CodeBehind when appending, then why doesn't it work when I'm removing?

PS.: I know I could use javascript for it, but I'd prefer the whole checking step to be at one place, instead of one half of it being .cs and the other half of it being javascript. But if I can't remove from the CodeBehind, then I'm going to use javascript, but I'm hoping there is a solution.

CodePudding user response:

Where in the page lifecycle have you implemented this? It sounds like a good first place to look.

It would also be helpful to see your code.

CodePudding user response:

Control.CssClass.Replace(" is-invalid", "");

That takes the string from the CssClass property, creates a new string without the is-invalid value, and then throws the new string away. The value of the property will not be changed.

If you want to modify the value of the property, you need to update it:

Control.CssClass = Control.CssClass.Replace(" is-invalid", "");
  • Related