Maintain features in a control after doing a PostBack

0

Greetings. It turns out that I have a Textbox that when it loses the focus it changes its background color, all this thanks to a function that I have over there in JavaScript . Later I have another Textbox that makes a PostBack that I need for a query to a database, and here is the problem:

when that second TextBox makes PostBack , the background color of the first one loses its property that it had acquired thanks to the JavaScript function. And it makes sense, I know.

But is there any way to make the PostBack not affect the characteristics of the controls that are acquired from the client side? Or maybe doing something in Page_Load ? And if the answer is in this last, I do not know exactly what.

To make me understand a little better, I tried this in a script :

 document.getElementById('<%=Label1.ClientID%>').innerHTML= "Nuevo_texto";

The above changes the text of a Label , is not it?

So far, normal, but if I then do a PostBack , the Label takes its default value.

How do I avoid this? Is it possible?

    
asked by Necroyeti 31.07.2017 в 19:47
source

1 answer

1

The way I could solve it was by saving the control status in another server control, such as a HiddenField field. Whenever a change is made in your control, you add the change as an attribute to the control of the server. At the time of doing the postback you read the control information and apply it to your control.

<asp:HiddenField ID="campo_nombre_estilo" runat="server />

<asp:TextBox runat="server" ID="nombreTextBox" />
<button type="button" onclick="modificarEstilo()">Cambiar estilo</button>

JS:

function modificarEstilo()
{
  document.getElementById("<%=campo_nombre_estilo.ClientId%>").attr("background", "red");
}

Then in the Page_Load , when doing postback you read the attributes of the HiddenField and you apply it to the control:

public void Page_Load(object sender, EventArgs e)
{
   if(!IsPostBack)
   {
     //...
   }

  nombreTextBox.Styles.Add("background", campo_nombre_estilo.Attributes["background"]);

}

When doing PostBack , webforms does not send the style information of each element to the server for how heavy each request would be for so much information.

    
answered by 31.07.2017 / 20:48
source