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(),
- Salary: $("#txtSalary1").val(),
- }
-
- $.ajax({
- type: "POST",
- url: '/employee/AddEmployees',
- data: JSON.stringify(employee),
- datatype: "json",
- cache: false,
- success: function (data) {
-
- },
- });
-
- });
-
- public ActionResult AddEmployees(Employee employee)
- {
- 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);
- }
- }
-
second approach :- failed. (worked 70% times earlier)
- $("#btnInsert").click(function () {
- debugger;
-
-
-
- var employee = {
- Name: $("#txtName1").val(),
- Salary: $("#txtSalary1").val(),
- }
- var model={
- "emp":employee
- }
- $.ajax({
- type: "POST",
- url: '/employee/AddEmployees',
- data:model,
- datatype: "json",
- cache: false,
- success: function (data) {
-
- },
- });
-
- });
-
- public ActionResult AddEmployees(Employee emp)
- {
- 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.