0

I have an API controller which has actions to get and post data. and I am trying to access GetProductById meyhod from ajax bu productId parameter is always equals to zero (0). When I want to call GetAll method with GET method everything is fine. JavaScript code is like below

var product = JSON.stringify({ productId: id });
        $http({
            method: 'POST',
            contentType: 'application/json',
            url: '/api/Product/ProductInfo',
            data: product
        }).then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log(response);
        });

And API Controller is like below

[Route("api/Product")]
public class ProductController : BaseController
{
    [HttpPost]
    [Route("ProductInfo")]
    public Product GetProductById([FromBody]int productId)
    {
        return UnitOfWork.GetRepository<Product>().FirstOrDefault(i => i.Id == productId);
    }
    [HttpGet]
    [Route("GetAll")]
    public string GetAll()
    {
        return "Can";
    }
}

Can anyone say why that case is happening?

1 Answer 1

1

Although you are sending back a string representation of { productId: id } when the model is binded in the post method in the controller it is expecting an int. productId is barely the argument of that method, it doesn't define the parameter name you're supposed to send. Try sending just the id in the body instead of that json body { productId: id }.

If you want to send back a json body then the proper representation should be a class like the following for your post action

class ProductModel
{
    int productId;
}

This would essentially make you able to parse your json payload the way you send it now, of course you can opt for custom model binders but that would be an overkill.

For example, if the id is 123 just use 123 as body, not { productId: 123 }

Sign up to request clarification or add additional context in comments.

4 Comments

I modified code. Neither I should call url like path?productId=1 nor I should use reference types instead of primitive types
Cool. That's essentially the right way to go given it's a post. :) Although you can use a keyvalue pair in these cases, no extra classes necessary anyway.
KeyValuePair? how can i send it from json or is it clear to get from api action?
Pardon me if I mislead you. I wanted to suggest something like the this. I can pretty much understand that I mislead you using KeyValuePair<TKey, TValue> types. Didn't intend to. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.