Home > Enterprise >  How to pass a model to controller through ajax?
How to pass a model to controller through ajax?

Time:09-01

I'm using ASP.NET Core 6 MVC. How to pass a model to controller through Ajax? I have read this, but I was confused and have tried with my code shown below, but without any luck. Any help is appreciated! Many thanks in advance.

This is my Ajax calls to controller:

const fd = new FormData($('#form-data')[0]);

const data = {};
fd.forEach((value, key) => (data[key] = value));

console.log(data);

$.ajax({
            type: 'POST',
            url:  '/User/Update_Me/',
            data: data,
            contentType: "application/json",
            success: function (result)
            {
               alert('horeee');
            },
            error: function (result)
            { 
               alert('error here');
            }

And this is my UserController:

[HttpPost]
[Route("/User/Update_Me")]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult Update_Me(Views.User.Data data)
{
    if (!ModelState.IsValid)
        return View(data);

    // Starts process here ...
}

CodePudding user response:

In your js code, The type of data is object, So you need to change your ajax like:

$.ajax({
            type: 'POST',
            url:  '/User/Update_Me/',
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function (result)
            {
               alert('horeee');
            },
            error: function (result)
            { 
               alert('error here');
            }
})

Then in action, You also need to add [FromBody] attribute.

public IActionResult Update_Me([FromBody]Views.User.Data data)
{
    if (!ModelState.IsValid)
        return View(data);

    // Starts process here ...
}
  • Related