Why ajax send parameters to controller is null?

I sending a post request to controller by ajax:

This is my code in cshtml file:

<script>
    $("#btnSeachAjax").click(function () {
        var token = $('input[name="__RequestVerificationToken"]').val();    
        $.ajax({
            url: '@Url.Action("Search")',
            data: { id: "1",title:"ba"},
            contentType: 'application/json',
            type: 'POST',
            headers: {
                "RequestVerificationToken": token
            },
            success: function (data) {
                $("#data").html(data);
            }
            ,
            error: function (req, status, error) {
                alert(error);
            }
        });
        return false;
    });
</script>

This is my code in controller:

 [HttpPost, ActionName("Search")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Search([FromBody] string id,string title)
        {
            var movie = await _context.Movies.FindAsync(id);
            return View(movie);
        }

Value of id , title in controller = null.

Why ajax send parameters to controller is null?

I using Asp.net mvc net core 3.1.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

public async Task<IActionResult> Search([FromBody] string id,string title)

Value of id , title in controller = null.

Based on your action method and accepted parameters, you can try to modify the Ajax code as below.

$.ajax({
    url: '@Url.Action("Search")'+'?title=ba',
    data: JSON.stringify("1"),
    contentType: 'application/json',
    type: 'POST',
    //...

Besides, you can create a viewmodel and modify your action accept a complex type parameter, like below.

public class MyData
{
    public string Id { get; set; }
    public string Title { get; set; }
}

Action method

public async Task<IActionResult> Search([FromBody] MyData myData)
{
    //...

On JS client side

$.ajax({
    url: '@Url.Action("Search")',
    data: JSON.stringify({ id: "1", title: "ba" }),
    contentType: 'application/json',
    type: 'POST',
    //...


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x