4

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.

5
  • 1
    An example of the type of session data you are wanting to pass would be helpful. Exposing the lot is never a good idea (security risk). Simple values can be injected into page elements as you have done. More complex data could (not recommended) be injected as JS literal objects. It all depends on what you want to do. Commented Feb 11, 2015 at 15:18
  • So would creating a session array specifically for passing to angular a better idea? Commented Feb 11, 2015 at 15:27
  • What sort of data are you wanting from the session into the page? Can you give an example, so my poor tired brain can chew on it? :) Commented Feb 11, 2015 at 15:28
  • Is there a specific reason you are even using session? MVC should be able to handle most passing of data using ViewData and TempData. Commented Feb 12, 2015 at 15:56
  • @DavidP I'm trying to find a cleaner way of passing the data into angular without having to shove all my ViewBag's into ng-init to initialize Commented Feb 12, 2015 at 16:00

2 Answers 2

1

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);
    }
);
Sign up to request clarification or add additional context in comments.

2 Comments

Can you share an example?
I made an edition to my answer. Please see if it may be helpfull.
0

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

Comments

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.