Med
Med

Reputation: 136

Passing ID from url to MVC Controller (AngularJS)

I'm new to AngularJS, trying to pass the ID from the url to MVC controller JSON method and then return the JSON to the angular scope.

Here is my MVC Controller:

public ActionResult Client(int clientid)
{
    return View();
}

public JsonResult GetClient(string clientid)
{   

    ClientDao clientDao = new ClientDao();

    Client client = clientDao.getClientById(int.Parse(clientid));

    return new JsonResult { Data = client, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

And here is my Angular .js file:

var app = angular.module('myapp', ['ngRoute']);

app.config(function ($routeProvider, $locationProvider) {
    $routeProvider
        .when('/Home/Client/:clientid', {
            controller: 'ClientCtrl'
        })
         .otherwise({
             redirectTo: "/Home/Index"
         })
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
});

app.controller("ClientCtrl", function ($scope, $http, $routeParams) {
    // alert($routeParams.clientid);
$http({
    url: "/Home/GetClient/",
    params: {clientid: $routeParams.clientid},
    method: "get"   
})
    .then (function (response) {
        $scope.client = response.data;
    })
});

The problem is that the parameter clientid in the $routeParams is always undefined. How should I fix this ?

Update: Here's how my link looks like: http://something.com/Home/Client/20

Upvotes: 0

Views: 1904

Answers (1)

Attila Szasz
Attila Szasz

Reputation: 3073

The way you defined your action in the MVC controller, assuming that the default Route is the only one defined, it expects your url to look like http://something.com/Home/Client?clientid=20

Solutions:

  1. Rename clientId to id
  2. Add another route in AppStart/RouteConfig that has a clientid param
  3. Use attribute routing and define your route like [Route("getclient/{clientid}")]

Upvotes: 1

Related Questions