Gesh
Gesh

Reputation: 333

How to retain a value set in javascript after postback

I have the following problem. I have a page and in the Document Ready event I call a web service that returns a string value. After that the value is assigned to a Label control (visible). After that I want to use the value in the Code Behind but I don't know how to get it.

All the events Page_load, Page_Prerender, ... have passed before the value has been retrieved from the service so I can't get it in any of them.

If I try to get it on a button click the page does a postback and loses the value.

I tried to find the control via Request.Form but it still returns nothing.

Upvotes: 1

Views: 9038

Answers (3)

KrishnaDhungana
KrishnaDhungana

Reputation: 2684

You can save value in Hidden Field

Aspx:

<asp:HiddenField ID="CustomHiddenField" runat="server" ClientIDMode="Static" />

In code behind file :

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "someval=" + this.CustomHiddenField.Value, true);

Jquery:

$(document).ready(function () {
var value= someval;
$('#htmlemement').val(value);

});

Upvotes: 0

Samiey Mehdi
Samiey Mehdi

Reputation: 9414

JQuery:

$(document).ready(function () {
    var ValueOFWebService = "sss";
    $('#hf').val(ValueOFWebService);
});

ASPX:

<input id="hf"  runat="server" type="hidden" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Code behind:

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Write(hf.Value);
}

Upvotes: 1

Nirmal
Nirmal

Reputation: 934

You can change value of label at client side but you will not get new value of label at server side because it is not editable. you can put hidden field for that an get value of that.

Upvotes: 0

Related Questions