Hima
Hima

Reputation: 41

Asp.Net Web API is not receiving Post data from angular

Please help me out.

I want to pass string to Post method of WebApi controller using $http method.But I am getting null string at controller side.

Here is my client side code.

$http({
        url: 'http://localhost/MyWebApi/api/home',
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        data: JSON.stringify({name: $scope.newProduct})

    }).success(function (data, status, headers, config) {
        $scope.products = data;
        $scope.newProduct = "";
        console.log(data);
    })
     .error(function (data, status, headers, config) {         
         console.log(data);
      });

And here is my WebApi controller

 [HttpPost]
        public IHttpActionResult Post([FromBody]string newProduct)
        {
            var db = new MVCEntities();
            db.Products.Add(new Product() { ProductName = newProduct });
            db.SaveChanges();
            var products = db.Products.ToList();
            return Ok();
        }

Thanks

Upvotes: 2

Views: 1404

Answers (2)

jpgrassi
jpgrassi

Reputation: 5742

You are getting null probably because your POST request doesn't match your method signature: Try this:

data: { newProduct: $scope.newProduct }

If it still doesn't work, try also removing the [FromBody] attribute from your controller:

public IHttpActionResult Post(string newProduct)

Upvotes: 2

Jehof
Jehof

Reputation: 35544

Your JSON does not match the method signature. There is no need for JSON, you can pass it in as normal string

data: $scope.newProduct

Or use a custom object, that matches your JSON and use it as parameter for your method, like

[DataContract]
public class NewProductData{

   [DataMember(Name="name")]
   public string Name {get;set;}
}

New method signature

public IHttpActionResult Post([FromBody]NewProductData newProduct)

Upvotes: 1

Related Questions