1

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

This application is an old web form and is not MVC Here is what I did

in my standalone JS ( Tried to post to the same aspx page my value which is true

$(document).ready(function () {
     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);
         }
     }); 
}

The test.aspx has this JS And in test.aspx.cs I defined the function so I could assign the true that i sent during post by Ajax to my session variable using the below method

[WebMethod]
protected void SetSessionVariable(string data)
{
   Session["myTest"] = data;
}

However I Get the following error Unknown web method SetSessionVariable [ArgumentException: Unknown web method SetSessionVariable. Parameter name: methodName] System.Web.Script.Services.WebServiceData.GetMethodData(String methodName) +626166 System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs eventArgs) +218 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +144 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +73'

Any suggestion would be much appreciated

7
  • 1
    Does this answer your question? asp.net web forms [WebMethod] Commented Sep 8, 2023 at 23:55
  • 1
    In the above link and within the link specified in the accepted answer, notice how it specifies the method as static, and it passes the name of the of the parameter and not just the value. Commented Sep 8, 2023 at 23:56
  • [WebMethod] protected static void SetSessionVariable(string value) { // Get the data from the client-side using a hidden field or a JavaScript variable and set the session variable HttpContext.Current.Session["myTest"] = value; } as you suggested changed to static and the parameter name is value , The same name as data: JSON.stringify({ value: 'true' }), in my Ajax call. I get below error see next comment plz Commented Sep 9, 2023 at 0:34
  • Request URL: localhost:xxxx/Support/Test.aspx/SetSessionVariable Request Method: POST Status Code: 500 Remote Address: [::1]:44310 Referrer Policy: strict-origin-when-cross-origin Commented Sep 9, 2023 at 0:36
  • So, it looks like the issue related to this post is fixed and you now have another issue. I think this post, how-to-allow-cors-for-asp-net-webforms-endpoint, may have the answer to your new issue. If not you should make a new post with the new issue. Commented Sep 9, 2023 at 0:45

1 Answer 1

1

Ok, so there are several issues here, some noted in comments.

First up:

The web method you call has to be "static". In other words, that bit of code has to run as "stand alone" code. There is no instance of the page class having been created here (and thus that web method can't reference controls on the given page).

Also, since the web method is static, and "independent" of the current web page class instance, then you have to reference session[] different.

Last but not least:

If you have friendly URL's on, then the routing page has to be changed, else your web method will not work.

So, let's get the bits and parts corrected here.

So, in the aspx page, the method will be defined like this:

 using System.Web.Services;   <--- don't forget this at top


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

    }

So, you must enable session in the above compiler directive.

And note how now you have to use the current Http context to get use of session.

Client-side code will be quite much as you have.

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

        <script>

            function mytest() {

                $.ajax({
                    type: "POST",
                    url: "ActiveImage.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>

So, for testing, we don't use the page on ready. Let's get the code working, and then "progress" towards having such code run on browser page load event.

Ok, last but not least, if you are using friendly URL's, then you need to open up the RouteConfig.cs, and set AutoRedirectMode = off.

 settings.AutoRedirectMode = RedirectMode.Off;

Note also how I used "V" in place of "v" for the parameter being passed ("value" vs "Value"). Parameters passed to the web method are case sensitive, and thus have to match.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this great detail explanation . This resolved my one original error but i get CORS error not sure why as it is teh same origin . I created another post as another user suggested I am closing this one and continue on that. Here is the link stackoverflow.com/questions/77071255/…. I hope you can give me some suggestions on it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.