0

I have the following method in Employee controller UpdateEmployee. I want to pass updated value of employee model from html to controller using javascript function. How can I pass model from javascript to Controller, please help

[HttpPost]
public IActionResult UpdateEmployee(Employee emp)
{
}

I want to pass the model from JavaScript to controller

var url = "/Employee/UpdateEmployee?

$.ajax({
  type: "POST",
  url: url,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (data) {

  },
  failure: function (response) {
    console.log(response.responseText);
  },
  error: function (response) {
    console.log(response.responseText);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
system threep
  • 139
  • 1
  • 2
  • 12
  • 1
    There isn't any javascript model shown to send. Whatever it is you need to send you need to use `data: JSON.stringify(myJSmodel)` – charlietfl Sep 13 '20 at 22:35

1 Answers1

1

If you want to get json data in action,you need to use [FromBody],here is a demo worked:

Controller:

 public class EmployeeController:Controller
    {
        [HttpPost]
        public IActionResult UpdateEmployee([FromBody]Employee emp)
        {
            return Json(emp);
        }
}

Model:

public class Employee
    {
        public int id { get; set; }
        public string name { get; set; }
    }

ajax:

<script>
        var url = "/Employee/UpdateEmployee"
        var datas = {
            id: 1,
            name: 'nm'
        }
        $.ajax({
            type: "POST",
            url: url,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(datas),
            success: function (data) {
                console.log(data)
            },
            failure: function (response) {
            console.log(response.responseText);
            },
            error: function (response) {
                console.log(response.responseText);
            }
        })
    </script>

result: enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • I thought that `[FromBody]` in a case like this was optional. Also, **never write your own JSON**. Use `JSON.stringify({"id":1,"name":"nm"})` – Phil Sep 14 '20 at 02:37