我试图找出将服务器会话数据从MVC Razor应用程序传递到Angularjs的最佳方法。
在ASP.net中,我们能够使用System.Web.UI.Page扩展一个类,创建一个字符串字典项,并对该数据进行json序列化,然后将该项传递给this.ClientScript.RegisterClientScriptBlock,但是我无法遵循相同的路径,因为我使用的是Razor。
目前我只是传递ViewBag.variableName并在ng-init中设置值,但这并不理想。所以我想到了几个想法。
是否最好设置一个使用角控制器获取将会话放入$scope.variable的ashx处理程序页的角服务?或者将会话传递到视图,然后以某种方式将其导入$scope?
从MVC Razor获取服务器会话变量的最佳方法是什么?
好的,我发布了下面的答案,但是我仍然很难将会话放到多个控制器的范围内。因为http.get是异步的,所以我无法获得动态的结果集。
发布于 2015-02-11 16:34:47
所以,这就是我最后的做法。我只是不知道这是不是最好的做法。基于注释,我指定要发送到角的会话项。
1)我创建了一个唯一的字典,它将数据传递给我的会话变量
private Dictionary<string, List<string>> _sessionDict
= new Dictionary<string, List<string>>();
2)我创建了一个fn()来帮助加快插入过程
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)我把数据插入我的字典
utility.addDictionarySession(_sessionDict, "test", "This is a test");
4)我将字典添加到会话中
Session.Add("jsPass", _sessionDict);
5)我创建了一个ashx处理程序页面来获取会话变量--这里是我的函数
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)我创建了一个获取ashx处理程序页的角服务。
// Load Session
getSession: function () {
return $http.get('../../handlers/getSessionData.ashx');
}
6)我创建了一个角控制器函数来调用服务并将项拉到一个$scope变量中,然后将函数设置为一个变量,然后执行函数调用。
var setSession = function () {
UtilityService.getSession().success(
function (results) {
$scope.session = results;
});
};
setSession();
7)我现在可以访问我的变量
{{session.test}
8)可以使用以下方法查看设置的所有项
9)我能够使会话进入范围here
发布于 2015-09-08 13:05:27
只需在页面控制器中创建一个专用操作,将服务器会话的值传递到JavaScript代码中的Ajax请求。
// 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);
}
);
https://stackoverflow.com/questions/28456722
复制相似问题