javascript - 使用 ASP.NET MVC 路由参数在 Angular js Controller 中显示未定义

标签 javascript angularjs asp.net-mvc asp.net-mvc-4

这是我使用 asp.net MVC 路由的 URL

http://localhost:23293/Exam?id=1

我想访问 Angular JS Controller 中的 id 参数

aoeapp.controller('ExamController', function ($scope, examservice, $routeParams) {
$scope.exams = [];
$scope.id = $routeParams.id;
alert($scope.id);
$scope.getAllexams = function (id) {

    examservice.getExamMaster(id).success(function (data) {
        $scope.exams = data;
    }).error(function (data, status, Xhr) {

        alert(Xhr);
    });
};
$scope.getAllexams(id);
});

这里 $scope.id 显示未定义

我的mvc路由只是默认路由

编辑 Angular 路线

aoeapp.config(function ($routeProvider) { 
    $routeProvider.when('/', { 
        controller: 'HomeController', 
        templateUrl: 'Pages/Home.html' 
    }).when('/Exam/:id', { 
        controller: 'ExamController', 
        templateUrl: 'Pages/Exam.html' 
    }).when('/Test/:id', { 
        controller: 'TestController', 
        templateUrl: 'Pages/Test.html' 
    }).otherwise({ redirectTo: '/' }); 
});

最佳答案

我用不同的方法解决了这个问题。我创建了一个 ViewBag 变量来存储查询字符串或 id,您也可以使用 model,然后将其传递到 Angular 方法中。通过代码你可以更清楚地理解这一点:

Razor View

<form name="ExamForm" ng-init="$scope.setQueryStringToScopeId(@ViewBag.Id)">
    ....
</form>

Angular Controller

aoeapp.controller('ExamController', function ($scope, examservice) {

    $scope.id = 0;
    $scope.setQueryStringToScopeId = function(id) {
        $scope.id = id;
    };
    ....
});

MVC Controller

public ActionResult Exam()
{
    ViewBag.Id = Request.QueryString["Id"];
    return View();
}

您还可以直接在 Razor View 中使用查询字符串。让我知道这是否适合您。

关于javascript - 使用 ASP.NET MVC 路由参数在 Angular js Controller 中显示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35376709/

相关文章:

javascript - 如何使用 jQuery 从 JSON 对象列出数组?

javascript - 选择多个文件时获取输入类型 ="file"值

javascript - 使用 Angularjs 有没有办法在 JavaScript 中只提交表单的各个部分?

javascript - 以 Angular 解决包裹的 promise

javascript - 将 C# 模型转换为 Angular 模型

c# - 如何用 Spark 返回部分 View ?

javascript - 将图像预加载到预缓存

javascript - Angular 作用域单例

c# - 在 MVC 中使用数据库连接包装方法

javascript - 三.JS FPS控制左右扫射