0

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

2
  • I think you are asking for trouble by having both the asp.net mvc route and the angular route pointing at the same location (/Home/Client). Is this not a SPA application? Commented Apr 5, 2016 at 15:36
  • Yes, at the end, it should be. I'm new to this stuff anyway, so I'm trying to figure out how to pass that ID to the server, get the JSON response, and repass that response to the scope. Commented Apr 5, 2016 at 15:56

1 Answer 1

1

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}")]
Sign up to request clarification or add additional context in comments.

1 Comment

I'm able to acess the JsonResult GetClient(string clientid), however the clientid is always null and here is the problem. If I give the string a static value, my code works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.