[英]Use ASP.NET MVC routing parameters showing undefined in angular js controller
這是我的網址,它使用asp.net MVC路由
http://localhost:23293/Exam?id=1
我想訪問angular js控制器中的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路由只是默認路由
編輯角度路線
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: '/' });
});
我有一個類似的問題,我的Angular路由被路由到我的MVC控制器。 我使用綜合路線修復了它:
將此路由添加到您的App_Start/RouteConfig.cs
:
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Angular",
url: "Exam/{*url}",
defaults: new {controller = "Angular", action = "Index" }
);
在Controllers/AngularController.cs
文件中執行以下操作:
[Route("Exam/{*url}")]
public ActionResult Index()
{
return View();
}
這應該攔截對/Exam
所有調用,並將它們重定向到您的Angular路由器。 您可能需要使用Route
屬性名稱來玩一玩。
我用另一種方法解決了這個問題。 我創建了一個ViewBag
變量來存儲查詢字符串或id,您也可以使用model
,然后將其傳遞給angular方法。 您可以通過以下代碼來更清楚地理解這一點:
剃刀視圖
<form name="ExamForm" ng-init="$scope.setQueryStringToScopeId(@ViewBag.Id)">
....
</form>
角度控制器
aoeapp.controller('ExamController', function ($scope, examservice) {
$scope.id = 0;
$scope.setQueryStringToScopeId = function(id) {
$scope.id = id;
};
....
});
MVC控制器
public ActionResult Exam()
{
ViewBag.Id = Request.QueryString["Id"];
return View();
}
您也可以直接在Razor View
使用查詢字符串。 如果這對您有用,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.