Showing posts with label Security Token Service. Show all posts
Showing posts with label Security Token Service. Show all posts

Tuesday, July 30, 2013

Ajax call to Page Methods

Folks,

Recently I got to work on a .NET based Security Token Service and faced an issue where I needed to call a web method from with in the page without creating a new session, normally whenever we use ajax call we get a new session which would redirect us back to the login page of the Application as it doesn't know whether the call was from the authenticated user or what.

Anyway, so I hope you all understand the issue. The main purpose of the function was to get the data from the session for a particular key, I know first thing that comes to your mind would be that I must have used

<%=Session['key']%>

Which is what we use all the time but no this time the scenario was different. I had to get the value because I had an Iframe in the page which was changing the value of that particular key. So what I did was, I googled a bit and got to know about PageMethods. So here it is how I used it


Paste this in your form tag:



<asp:ScriptManager ID="ScriptManagerMain" runat="server" EnablePageMethods="true"
        ScriptMode="Release" LoadScriptsBeforeUI="true">
    </asp:ScriptManager>

And use the javascript:

  function onSuccess(data) {
            window.location = data;
        }
        function onFailure(error) {
            window.location = 'where-ever-I-wanted-it-to-go';
        }
        function GetCurrentSessionValue() {
            // call server side method
            PageMethods.GetSessionValue(onSuccess, onFailure);
        }

This is my Code Behind where I wrote this method.

 [WebMethod]
        public static string GetSessionValue()
        {
           return HttpContext.Current.Session["RedirectUrl"].ToString();
        }


I hope it helps. For any query just post a comment and I will get back to you.