I'm refactoring my ASP .net core project and I want to make use of some Ajax calls, but I'm facing the following problem: when I try to send a request to a method in a controller of my project but it doesn't work.

I have a modal with the following button:

<button onclick="reviewRestaurant(@item.RestaurantId)" class="btn btn-outline-primary">Add review</button>

the reviewRestaurant() function looks like this:

function reviewRestaurant(restaurantId) {
    let rating = $("input[type=radio]:checked").val();
    let review = $('textarea').val();

    let data = { restaurantId, rating, review };

    $.ajax({
        type: "POST",
        url: `/Restaurants/Review`,
        data: JSON.stringify(data),
        success: function (res) {
           // TODO: work on this later
        },
        error: function (err) {
            console.log(err);
        }
    });
}

And the method that I wanna call in the Restaurants controller looks like so:

[Authorize]
[HttpPost]
public async Task<IActionResult> Review(int restaurantId, string rating, string content)
{
    var username = this.User.Identity.Name;
    await this.restaurantsService.Review(restaurantId, username, rating, content);
    return this.RedirectToAction("Details", new { id=restaurantID });
    // the output of this method will be refactored later once I manage to get to it
}   

The problem is I cannot reach the Review method in the controller. I get the 400 status code and I don't know how to fix it. I tried using DTO and [FormData] attribute for the method parameters and tried passing the data without stringifying it still nothing works.

If anyone can help me I would be very grateful. I'm relatively new to ajax calls and simply cannot see where my mistake is.

2 Answers

0
Sinan Bozkuş On

You can try this solution:

Create a common class for your parameters (int restaurantId, string rating, string content) and use FromBody. => Review([FromBody] YourClassName)

And write this parameters in your ajax code. contentType: 'application/json; charset=utf-8', data: 'json'

I hope it will help you.

0
Tao Zhou On

Here is a working demo which I test.

@section Scripts
    {
    <script>
            function reviewRestaurant(restaurantId) {
                let rating = $("input[type=radio]:checked").val();
                let content = $('textarea').val();
                let data = { restaurantId, rating, content };
                $.ajax({
                    type: "POST",
                    url:'/Restaurants/Review',
                    data: data,
                    success: function (res) {
                        // TODO: work on this later
                    },
                    error: function (err) {
                        console.log(err);
                    }
                });
            }
    </script>
}