0

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.

1

1 Answer 1

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

5 Comments

And you can know more information about "Model Binding in ASP.NET Core" from this doc: learn.microsoft.com/en-us/aspnet/core/mvc/models/…
the solution 1, only send title, i had send ok by MyData class.
Case only send 1 parameter, i have to send by URL?
the solution 1, only send title It works for me, please check the actual request and posted data in browser f12 developer tools Network tab.
Case only send 1 parameter, i have to send by URL? Passing these two parameters trough querystring is ok, but you need to remove [FromBody] attribute from id parameter.

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.