i am using ajax for 4 years , but seriously i couldn't understand it completely when it comes to post data to controller.
for me its pure luck, sometimes some method works sometimes something other and sometimes nothing works.
I have below example
Approach 1. Failed here(though it works sometimes,idk why)
- $("#btnInsert").click(function () {
- debugger;
- var employee = {
- Name: $("#txtName1").val(), // have value
- Salary: $("#txtSalary1").val(), // have value
- }
- $.ajax({
- type: "POST",
- url: '/employee/AddEmployees',
- data: JSON.stringify(employee), // have values
- datatype: "json",
- cache: false,
- success: function (data) {
- },
- });
- });
- public ActionResult AddEmployees(Employee employee) // values are null
- {
- try
- {
- if (ModelState.IsValid)
- {
- var azuS = client.PostAsJsonAsync("api/Employee", employee).Result;
- if (azuS.IsSuccessStatusCode)
- {
- return Json(employee, JsonRequestBehavior.AllowGet);
- }
- }
- return RedirectToAction("GetAllEmployee", "Employee");
- }
- catch (Exception ex)
- {
- return Json(ex.Message);
- }
- }
-
- $("#btnInsert").click(function () {
- debugger;
- var employee = {
- Name: $("#txtName1").val(), // have value
- Salary: $("#txtSalary1").val(), // have value
- }
- var model={
- "emp":employee
- }
- $.ajax({
- type: "POST",
- url: '/employee/AddEmployees',
- data:model, // have values
- datatype: "json",
- cache: false,
- success: function (data) {
- },
- });
- });
- public ActionResult AddEmployees(Employee emp) // values are null
- {
- try
- {
- if (ModelState.IsValid)
- {
- var azuS = client.PostAsJsonAsync("api/Employee", employee).Result;
- if (azuS.IsSuccessStatusCode)
- {
- return Json(employee, JsonRequestBehavior.AllowGet);
- }
- }
- return RedirectToAction("GetAllEmployee", "Employee");
- }
- catch (Exception ex)
- {
- return Json(ex.Message);
- }
- }
-
Approach 3:- query string (no data, directly construct url) (Success here)
- $.ajax({
- type: "POST",
- url: '/employee/AddEmployees?Name='+employee.Name+"Salary="+employee.Salary,
- datatype: "json",
- cache: false,
- success: function (data) {
- },
- });
what is wrong with method 1 and 2.
Yes i tried with contentType:application/json;charset:utf-8;
please tell me a way which works in every situation no matter what.


Atish Misal7 reputationPosted Dec 1, 2020, 7:49 AM EST
Sachin SinghRank #66 · 26.2K reputationPosted Dec 1, 2020, 8:10 AM EST
Sachin SinghRank #66 · 26.2K reputationPosted Dec 3, 2020, 2:38 AM EST
Jignesh KumarRank #91 · 22.9K reputationPosted Dec 3, 2020, 2:52 AM EST
Sachin SinghRank #66 · 26.2K reputationPosted Dec 3, 2020, 3:13 AM EST
Jignesh KumarRank #91 · 22.9K reputationPosted Dec 3, 2020, 3:34 AM EST
Jaimin ShethiyaRank #177 · 13.7K reputationPosted Dec 3, 2020, 6:40 PM EST
can you please try the below and checked it's working or not.
public ActionResult AddEmployees([FromBody]Employee emp) or also can you checked the Employee class is there not any datatype mismatched you have paased the values.
Thanks