显示角度JS控制器未定义使用ASP.NET MVC路由参数

显示角度JS控制器未定义使用ASP.NET MVC路由参数

问题描述:

这是我的网址这是使用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路线到这个问题。 –

我有一个类似的问题,在我的角度路线被路由到我的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,然后将它传递给角度方法。

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)'并且它会工作。 –