Payam Sh
Payam Sh

Reputation: 601

Get value of ASP.NET hidden field from code behind using JQuery

I want to set the value of an ASP.NET hidden field with JQuery and then read its value from ASP.NET code behind.

I have this code so far but when I traced it I found out that it changes the value of hidden field, but code behind gets the previous value of hidden field!

Any suggestions? Thanx in advance.

ASPX:

<input type="hidden" id="SubmitHiddenField" name="SubmitHiddenField" clientidmode="Static" runat="server" />

JQuery:

function func() {
    if (invalid) {
        $("#<%= SubmitHiddenField.ClientID %>").val("false");
        alert("false");
    }
    else {
        $("#<%= SubmitHiddenField.ClientID %>").val("true");
        alert("true");
    }
}

Code behind:

ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "func()", true);
string s;

if (SubmitHiddenField.Value == "true")
     s = "Yes";
else if (SubmitHiddenField.Value == "false")
     s = "No";

Upvotes: 0

Views: 1264

Answers (1)

Amit Joki
Amit Joki

Reputation: 59232

The problem is you're checking it in the block where you've set the javascript to execute. When your if condition is executed, func is not actually called, as you suppose the case is.

The func will only be called after the Page_Load and other events are over an HTML is sent to the client. Only then the func will be executed.

So, you must only check the value after a postback. For example, you could add a button which would execute a handler in the code behind, in which you can check for the hidden field's value.

Upvotes: 1

Related Questions