user1189352
user1189352

Reputation: 3885

Angular & ASP.NET MVC - Parameter is null when I pass a parameter to my backend Controller

If you look at the parameter of my ASP.NET MVC Controller clientId, it's always null.

the only way i can get it to not be null and actually pass the data through successfully is to create a class... but that gets tedious and I can't create a class for every backend function i make just to get this to work.

Is there a way to pass data successfully without creating a class?

Thank you for any help

Angular Factory

PlaylistsFactory.getUsersForClient = function (clientId) {
return $http({
    method: 'POST',
    url: '/Show/GetUsersForClient',
    data: JSON.stringify(clientId)
  });
};

Angular Controller

PlaylistsFactory.getUsersForClient(clientId)
  .success(function (userList) {
    console.log('success!');
  });

ASP.NET MVC Controller

public JsonResult GetUsersForClient(string clientId)  //clientId is always null unless i create an object
{
  ...
}

Upvotes: 0

Views: 2359

Answers (2)

Dudemanword
Dudemanword

Reputation: 704

Try making your JSON parameter match the name of your C# parameter as well as encasing that in the data payload as JSON:

return $http({
    method: 'POST',
    url: '/Show/GetUsersForClient',
    data: {clientId: JSON.stringify(clientId)}
  });
};

Upvotes: 2

sebastian
sebastian

Reputation: 843

i would recommend that you follow the rules of a RESTful API.

This means you should use the HTTP verbs like GET (getting data), POST (updating data), PUT (creating data), DELETE (deleting data). See http://www.tutorialsteacher.com/mvc/actionverbs-in-mvc

Then you could also add the parameter you want to pass into the route of your API: /Show/GetUsersForClient/{clientId}. See http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

In this case you disengage the problem of sending data in the body without having a ViewModel on the MVC-Controller side.

When you want to proceed with your solution, then try creating the Object before sending it:

PlaylistsFactory.getUsersForClient = function (clientId) {
var payload = { clientId: clientId }   
return $http({
          method: 'POST',
          url: '/Show/GetUsersForClient',
          data: payload
       });
};

MVC / WebAPI also sometime choke when the content-type in the request header is text/plain or application/json. For example: a json-object will not be recognized properly by .Net when sent in text/plain.

Upvotes: 0

Related Questions