D T
D T

Reputation: 3756

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.

Upvotes: 0

Views: 1528

Answers (1)

Fei Han
Fei Han

Reputation: 27825

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',
    //...

Upvotes: 1

Related Questions