这是我使用 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/