简体   繁体   中英

How to pass a server session from Razor MVC C# to Angularjs?

I'm trying to figure out the best method of passing server session data from a MVC Razor application into Angularjs.

In ASP.net we were able to extend a class using System.Web.UI.Page create a string dictionary item and json serialize that data then pass that item to this.ClientScript.RegisterClientScriptBlock, but I am unable to follow the same path because I am using Razor.

I currently am just passing ViewBag.variableName and setting the value in ng-init, but this is not ideal. So a couple of ideas I have come to mind.

Would it be better to set up an angular service that fetches an ashx handler page that puts the session into a $scope.variable using angular controller? Or pass the session through to the view and then somehow get it into $scope?

What is the best method of getting server session variables into angular from MVC Razor?

Ok, I posted my below answer, but I'm still having trouble getting the session into scope of my multiple controllers. Because http.get is asynchronous and I can't get the results set to be dynamic.

Just create a dedicate action in your page controller to get the value from the server session to a JavaScript Ajax request inside your AngularJs code.

// Action to return the session value. This method should be inside a controller class.
public object GetSession(string sessionName)
{
    return Session[sessionName];
}

// JavaScript code to retrieve session "TEST":
$http.get('action/url/' + "TEST").
    success(function (sessionValue) {
        alert('Session "TEST" has the following value: ' + sessionValue);
    }
);

So here is the round about way I ended up doing it. I just don't know if it is the best practice or not. Based off the comments I specify what session items I want to send to angular.

1) I created a unique dictionary that is going to pass the data to my session variable

private Dictionary<string, List<string>> _sessionDict 
    = new Dictionary<string, List<string>>();

2) I created a fn() to help speed up the insert process

public static void addDictionarySession(
  Dictionary<string, List<string>> sessionDict, string key, string value)
{
  List<string> stringValue = new List<string>() { value };      
  sessionDict.Add(key, stringValue);
}

3) I inserted the data into my dictionary

utility.addDictionarySession(_sessionDict, "test", "This is a test");

4) I added the dictionary to the session

Session.Add("jsPass", _sessionDict);

5) I created an ashx handler page to get the session variables here is my function

 private void getSessionVariables()
{
  Dictionary<string, string> sessionData = new Dictionary<string, string>();

  // Retrieve Session that is stored in dictionary
  Dictionary<string, List<string>> sessionDict =
    _context.Session["jsPass"] as Dictionary<string, List<string>>;

  if (sessionDict != null)
  {
    foreach (KeyValuePair<string, List<string>> entry in sessionDict)
    {
      // Set the Value of the item
      foreach (string value in entry.Value)
      {
        sessionData.Add(entry.Key, value.ToString());
      }
    }
 }

 // _context is just my private HttpContext variable I set at the beginning of the class
 utility.httpContentWrite(_context, sessionData); 
}

5) I created an angular service that fetches an ashx handler page

// Load Session
getSession: function () {
  return $http.get('../../handlers/getSessionData.ashx');
}

6) I created an angular controller function to call the service and pull the item into a $scope variable, I set the function to a variable then executed the function call

var setSession = function () {

  UtilityService.getSession().success(
  function (results) {
    $scope.session = results;
  });

};
setSession();

7) I can now access my variable

{{session.test}}

8) You can view all the items you have set using this

 <div ng-repeat="(key, value) in session"> <span>{{key}} : {{value}}</span> </div> 

9) I was able to get the session into scope here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM