Search code examples
c#asp.netpagemethods

Passing variable to server-side then back to client side without postback or reload


Is there a way to pass values from client side to server-side, server side process this value, then return it to client side without reload or postback?

I am using ajax to pass the value to server side. Here is my client side code:

var baseUrl = '<%= ResolveUrl("~/") %>';
$.ajax({
    type: "POST",
    url: baseUrl + "Pages/TeamTimeTest/teamtime.aspx/setjson",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({
        strpath: $("#hdnfld").val()

    }),
    success: function (data) {
    alert(data);
    },
    error: function (response) {
        console.log(response);
    }
});

Here is my code behind code:

[WebMethod(EnableSession = true)]
public static string setjson(string strpath)
{
    HttpContext.Current.Session["strDwnPath"] = strpath;
    var val = HttpContext.Current.Session["strDwnPath"].ToString();
    return val;
}

It returns undefined for me. But when I reload it gives me the correct value. Is there a chance that I could have that value even without reloading?


Solution

  • HttpContext.Current.Session["strDwnPath"] = strpath;
    var val = HttpContext.Current.Session["strDwnPath"].ToString();
    return val;
    

    I should have done this instead.

    var val = strpath;
    return val;
    

    All i need here is to get the returned value and it did without reload.