PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How to pass a model to controller through ajax?

 September 06, 2022     ajax, asp.net-core-6.0, asp.net-core-mvc, c#     No comments   

Issue

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 ...
}

Solution

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 ...
}


Answered By - Xinran Shen
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing