在Razor中获取AnonymousID

时间:2015-11-15 13:30:14

标签: angularjs asp.net-mvc razor

我想在HttpContext.Current.Request.AnonymousID中获取Razor个用户,然后以这种方式将其发送到控制器中的操作:

<script>
 app.controller('loginController', function ($http, $scope, $location, $rootScope) {
    $scope.login = function () {

        //Send Anonymous to UserLogin action
        $http.post("/Accounts/UserLogin?anonymous="+AnonymousId, $scope.model).success(function (response) {
            $scope.message = response;

            window.location = '/';
            $rootScope.ShowSpinner = false;
        });
    }
});
</script>

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

在剃须刀中你可以拥有类似

的东西
@{
    // Just to make my expression smaller
    var anonymousId = HttpContext.Current.Request.AnonymousID;
}
<script>
    angular.module("someModule").value("anonymousId", "@anonymousId" );
</script>

注意注射Razor是正常的。如果失败,请尝试换行(),如"@(anonymousId)"。唯一的技巧是我只是将值包装在引号中,以便它是JavaScript中的字符串。

然后您可以将此值注入Angular控制器:

<script>
 app.controller('loginController', 
        function ($http, $scope, $location, $rootScope, anonymousId) {
            $scope.login = function () {

            //Send Anonymous to UserLogin action
            $http.post("/Accounts/UserLogin?anonymous="+anonymousId, $scope.model)
                .success(function (response) {
                    ...
            });
       }
});
</script>

当然你也可以直接在控制器中写它......

....
    $http.post("/Accounts/UserLogin?anonymous=" 
              + "@(HttpContext.Current.Request.AnonymousID)", $scope.model).
....