FindControl is unable to find Hidden Control on aspx Page Connected to Master inside static Web Method

I am having aspx page connected to Master page. On aspx page I am having asp:HiddenField. There is Static Web Method on aspx page and I have called is via jQuery json request. In this Web Method the hidden field is not accessible. I want to update the value of Hidden field with session value inside Web Method.

Below is my code:

HTML (on aspx page connected with Master)
<asp:HiddenField ID=”hdnLoggedinUser” runat=”server” />

Web Method:
[WebMethod(true)]
public static string welcomeuser()

{
Page page = (Page)HttpContext.Current.Handler;
HiddenField hdnUser = (HiddenField)page.FindControl(“hdnLoggedinUser”);
hdn
if (HttpContext.Current.Session[“UserName”] != null)
{
if (hdnUser != null)
{
string m, r;
m = (String)HttpContext.Current.Session[“UserID”];
r = (String)HttpContext.Current.Session[“UserName”];
hdnUser.Value = r;
}
}

var usr = HttpContext.Current.Session[“UserName”].ToString();
return usr;
}

jQuery:
$.ajax({
type: “POST”, //GET or POST or PUT or DELETE verb
url: “../DemoApp/admManageAccess.aspx/welcomeuser”,
data: {}, //Data sent to server
contentType: “application/json; charset=utf-8”,
dataType: “json”, //Expected data format from server
async: false,
beforeSend: function () {

},
success: function (data, Type, xhr) {//On Successfull service call
if (data.d != ”) {
$(‘#spnUserName’).text(‘Welcome : ‘ + data.d);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);

},
complete: function () {

},
failure: function () { }
});

In web method if (hdnUser != null) this line is getting null. It is not reading Hidden field on the page 

 

Read more here: Source link