2

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

1
  • 1
    try replace name with newProduct inside JSON.stringify({name: $scope.newProduct}) Commented Jan 21, 2016 at 10:09

2 Answers 2

2

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

Comments

1

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)

2 Comments

I tried this but it is not working.I'm still getting null
@Hirma Try Using content-type "text/plain" if using my first approach

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.