Cambiar asp: etiqueta con jQuery y luego acceder en código subyacente

I know, crazy right.

So I have an asp label and I want to fill it with jQuery. Later, in the codebehind I want to access this text for something else.

Lo que tengo es:

<asp:Label ID="myLabel" runat="server" />
<asp:Button ID="clickMe" runat="server" Text="Click!" OnClientClick="runMe();" 
   OnClick="clickMe_Click()" />

<script language="javascript" type="text/javascript">

   function runMe () {
      $("#<%=myLabel.ClientID").text("here");}
</script>

protected void clickMe_Click(object sender, EventArgs e)
{
   string isIt = myLabel.Text;
}

So if I put a breakpoint on whatever code follows 'isIt' definition and look at it, isIt="". Is there a way to make this work? I'm guessing since jQuery's acting on the html it is actually altering the not the actual ASP.NET label.

preguntado el 01 de febrero de 12 a las 01:02

3 Respuestas

Trata

$('#<%= myLabel.ClientID %>').html("here"); 
(This should work in all the browsers)

When I want to pass the value to the code behind page, I generally use a HiddenField and populate it using .val() in Jquery. I can then access its value in the code behind using HiddenField1.Value

Respondido 01 Feb 12, 05:02

Specifically your point about HiddenFields (the label thing didn't work). Thanks! - ScottieB

Yes, the value that you assign to label using Jquery will not be available in the code behind, hence you need to use hiddenfield. :) - NomadTraveler

Trata .val() en lugar de .text()

Edit: Since ASP.NET controls are rendered with prefixes you may also want to consider the termina con selector.

$('span[id$="myLabel"]').val("here");

Respondido 01 Feb 12, 05:02

I totally missed the most obvious problem. You're trying to get the value of a Label control, not a TextBox. Labels are rendered as spans and are not posted back to the server. I can't remember if Labels have the AutoPostBack property, if they do set that, otherwise you need to make it a TextBox or hidden field. - Terry

Yeah, you hit the nail on the head. I used Somya's HiddenField approach but I imagine a hidden textbox would do the trick as well. - ScottieB

An asp:Label element in the browser is rendered as a span element. So, setting the value would not work on it. We should either set the inner Text or inner Html of the asp:label or span element if working with Jquery/javascript. Like below:

$("#<%= myLabel.ClientID %>").text("MY UPDATED TEXT");
$("#<%= myLabel.ClientID %>").html("MY UPDATED HTML");

Respondido 28 ago 19, 00:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.