TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Sachin Singh
7
55.8k
82.8k
post data to MVC Controller from view using Ajax.
Dec 1 2020 12:26 PM
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);
}
}
second approach :- failed. (worked 70% times earlier)
$(
"#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.
Reply
Answers (
7
)
calculate factorial error.
My password unmasking is working but not the way I want it to