2016-02-13 87 views
1

這是我的網址這是使用asp.net MVC路由顯示角度JS控制器未定義使用ASP.NET MVC路由參數

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

我想訪問ID參數在JS角控制器

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: '/' }); 
}); 
+0

Angular不關心你的服務器端路由。你的_Angular_路線是什麼? –

+0

好的,但是如果我使用角路由而不是與MVC路由衝突,並且它不起作用 –

+0

您可以在兩側使用路由,但是您的Angular應用只關心Angular路由。添加您的Angular路線到這個問題。 –

回答

0

我有一個類似的問題,在我的角度路線被路由到我的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屬性名稱來玩一個小號。

0

我用不同的方法解決了這個問題。我創建了一個ViewBag變量來存儲查詢字符串或id,也可以使用model,然後將它傳遞給角度方法。

Razor視圖

<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中使用查詢字符串。讓我知道這是否適合你。

+0

中更改如果我在$ scope.setQueryStringToScopeId = function(id){ $ scope。 id = id; alert($ scope.id); };在函數內部正常工作,但是在這個函數之外再次顯示0值 –

+0

我將不得不看到你的代碼,但是一旦'$ scope.setQueryStringToScopeId'被執行,你可以'alert($ scope.id)'並且它會工作。 –