0

This is from asp.net 5 / mvc 6. I have two controller methods, each takes a single parameter and each returns a string. One method takes a string parameter and the other takes a simple object. The method that takes the string parameter does not work (the value for the incoming parameter is always null). The call that passes in the simple object does work. I am making the calls to these methods from inside an angular controller using the $http service. I must be doing something wrong that is very simple, but I don't see it.

Here is the code for the controller class:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    [HttpPost("PostWithStringParam")]
    public string PostWithStringParam([FromBody] string val)
    {
        return val ?? "<null>";
    }

    [HttpPost("PostWithInputparam")]
    public string PostWithInputParam([FromBody] TestInputClass val)
    {
        string ret = "<null>";

        if (val != null)
        {
            ret = $"First Name: {val.Name}, City: {val.City}";
        }

        return ret;
    }
}

Here is the relevant code from the angular controller. Note the the "go" function is wired up to ng-click from a button.

    vm.inputObject = {
        name: "George",
        city: "Chicago"
    }

    vm.inputString = "some data";

    var callApi = function(url, data) {

        $http({
            method: "POST",
            url: url,
            data: data
        }).then(
            function (result) {
                alert(result.data);
            },
            function (error) {
                alert(error.status);
            }
        );
    }

    var callStringApi = function() {

        var url = "api/values/PostWithStringParam";

        callApi(url, vm.inputString);
    }

    var callObjectApi = function () {

        var url = "api/values/PostWithInputParam";

        callApi(url, vm.inputObject);
    }

    vm.go = function() {

        callStringApi();
        callObjectApi();
    }

Can someone please tell me why the method that takes the input string doesn't work??

Thanks!

Greg P
  • 107
  • 1
  • 9

1 Answers1

1

You need to strinfigy the data and specify the contentType as application/json when sending data. The default model binder will be able to map the posted data then.

var callApi = function(url, data) {

    $http({
        method: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType:"application/json"
    }).then(
        function (result) {
            alert(result.data);
        },
        function (error) {
            alert(error.status);
        }
    );
}
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Cool. [Here](http://stackoverflow.com/questions/20226169/how-to-pass-json-post-data-to-web-api-method-as-object) is an extensive post to cover all use cases when posting to web api – Shyju Jul 18 '16 at 14:47