1

I'm a little confused as to how AngularJS is POSTing data to my WebAPI controller. Normally, when I would POST data from AngularJS to an MVC controller, I would do something like this:

var data = { "value": "some string" }; $http.post('/api/products', { data }).success(function () {... 

However, in the WebAPI controller, the string value is always coming back as null.

Do I need to post the data a little differently when passing data to a web api controller?

Here is the method in my controller:

 [HttpPost] public void Post([FromBody]string value) { ..... } 

edit Not sure if this helps, but this is the header from Fiddler:

POST http://localhost:58167/api/products/ HTTP/1.1 Host: localhost:58167 Connection: keep-alive Content-Length: 11 Accept: application/json, text/plain, / Origin: http://localhost:58167 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36 Content-Type: application/json;charset=UTF-8 Referer: http://localhost:58167/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.8

some string

10
  • see this post...stackoverflow.com/questions/16621706/…
    – Prashant
    CommentedSep 2, 2015 at 16:37
  • @Prashant Yea, I read that post already...including a few others. It appears that I'm doing everything correctly but the value always shows as null. If I'm using [FormBody] then I don't need to use Stringify, correct? I
    – Anonymous
    CommentedSep 2, 2015 at 16:40
  • did you give content type as JSON in your header
    – Prashant
    CommentedSep 2, 2015 at 16:45
  • @Prashant Yes -- I tried that too.
    – Anonymous
    CommentedSep 2, 2015 at 16:47
  • 1
    Perhaps change your Web API from accepting a string to accepting a model object, such as public class Product { public string Value {get; set;} }
    – mason
    CommentedSep 2, 2015 at 17:10

1 Answer 1

1

Change your Web API to accept a complex type (model) instead of a string.

public class Product { public string Value {get; set;} } [HttpPost] public void Post([FromBody]Product product) { Debug.WriteLine(product.Value); } 

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.