[英]How to pass a server session from Razor MVC C# to Angularjs?
我试图找出将服务器会话数据从MVC Razor应用程序传递到Angularjs的最佳方法。
在ASP.net中,我们能够使用System.Web.UI.Page扩展类,创建一个字符串字典项,然后json对该数据进行序列化,然后将该项传递给this.ClientScript.RegisterClientScriptBlock,但是我无法遵循相同的路径,因为我正在使用Razor。
我目前只是传递ViewBag.variableName并在ng-init中设置值,但这并不理想。 所以我想到了两个想法。
设置一个角度服务来获取ashx处理程序页面,使用角度控制器将会话放入$ scope.variable会更好吗? 还是将会话传递到视图,然后以某种方式使其进入$ scope?
从MVC Razor将服务器会话变量转换为角度的最佳方法是什么?
好的,我发布了下面的答案,但是仍然无法使会话进入我的多个控制器的范围。 因为http.get是异步的,所以我无法将结果设置为动态的。
只需在页面控制器中创建一个专用动作即可将值从服务器会话获取到AngularJs代码内的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);
}
);
因此,这是我最终完成此操作的方式。 我只是不知道这是否是最佳实践。 基于注释,我指定了要发送到angular的会话项目。
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)您可以使用此按钮查看已设置的所有项目
<div ng-repeat="(key, value) in session"> <span>{{key}} : {{value}}</span> </div>
9)我能够在这里将会议纳入讨论范围
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.