skip to Main Content

I would like to set a session variable in code behind so after received an ajax call result based on the result of that set a session variable.

This application is old webform and is not MVC Here is what I did
Below is my Test.aspx

<asp:Button ID="cmdTest" runat="server" Text="Set session value"          
 OnClientClick="mytest();return false"/>

<Script>
    function myTest() {
        console.log("Document is ready.");
        $.ajax({
            type: "POST",
            url: "CheckBrowser.aspx/SetSessionVariable",
            data: JSON.stringify({ value: 'true' }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                // Handle the server's response (if needed)
                console.log("success");
            },
            error: function (error) {
                console.log("AJAX Error: " + error);
            }
        });
    }
</script>

this is my Test.aspx.cs code

[WebMethod(enableSession: true)]
public static void SetSessionVariable(string value)
{
    HttpContext.Current.Session["myTest"] = value;
    Debug.Print("session value set");
}

however I get Request URL: localhost:44310/Support/Test.aspx/SetSessionVariable Request Method: POST Status Code: 500 Remote Address: [::1]:44310 Referrer Policy: strict-origin-when-cross-origin
see blow image of network trafic
enter image description here
This is strange as my origin is the same and i just from my aspx page perform an ajax call to set a variable in the same aspx code behind. I am not sure what i am missing any help will be much appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you for all the explanation above today I figured out why this is happening. It is because I had made the SetSessionVariable method in code behind Protected. It should have been public. It is interesting. As I thought, js in aspx should have access to aspx.cs protected methods. I think I can close this question. Thanks for the follow-up


  2. I suggest you post MORE of your markup.

    So, let’s create a sample web page. We will call it CheckBrowser.aspx.

    And our markup is now this:

    <form id="form1" runat="server">
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js">
        </script>
    
        <div>
            <input id="Button1" type="button" value="Set session value"
                onclick="SetValue();return false;" />
            <br />
    
            <input id="Button2" type="button" value="get session value"
                onclick="GetValue();return false;" />
    
            <script>
                function SetValue() {
                    $.ajax({
                        type: "POST",
                        url: "CheckBrowser.aspx/SetSessionVariable",
                        data: JSON.stringify({ value: 'Hello World' }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            // Handle the server's response (if needed)
                            console.log("success");
                            alert("Session value set")
                        },
                        error: function (error) {
                            console.log("AJAX Error: " + error);
                        }
                    });
                }
    
                function GetValue() {
                    $.ajax({
                        type: "POST",
                        url: "CheckBrowser.aspx/GetSessionVariable",
                        data: "{}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            // Handle the server's response (if needed)
                            alert("Session value from server = " + response.d)
                            console.log("success");
                        },
                        error: function (error) {
                            console.log("AJAX Error: " + error);
                        }
                    });
                }
    
    
            </script>
    
        </div>
    </form>
    

    So, note how we included the jQuery library. (It is required).

    So, when we run the above, we get/see this:

    enter image description here

    So, with the posted code, the above works just fine.

    This means that your supplied information is insufficient to determine why the above code works, and your code does not.

    I would as noted try hitting f12 for the browser tools, select console, and see what the browser developer mode shows.

    I would as note, consider creating a new test browser page, change the URL’s used in the ajax post example and see if that works.

    In other words, we the readers and people here are un-able to re-produce your error. As a result, you have to provide more of your page markup, since the above sample works just fine.

    I also for this test suggest using HTML buttons, and not asp.net ones, since any error in your JavaScript code will in most cases result in a page post-back, and that hides your ability to see the error message. Using the above HTML button with a return false will not cause a page post-back, and that should allow you to see the error(s) in any JavaScript code you have.

    As noted, it is VERY important information if your site has friendly URL’s turned on, since that will often prevent simple ajax calls from working.

    If using friendly URL’s, then you need to open up the RouteConfig.cs, and set AutoRedirectMode = off. That is this line of code:

    settings.AutoRedirectMode = RedirectMode.Off;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search