I am beginner and trying to update my record by using Ajax call in Entity Framework MVC. I am getting idtoSearch
successfully but not getting std.FirstName
and std.LastName
at controller side. As you can see in my code here
[HttpPost]
public ActionResult UpdateStudent(Student std, int idtoSearch) {
using (StudentContext db = new StudentContext()) {
Student updatestd = db.Student.Find(idtoSearch);
if (!string.IsNullOrWhiteSpace(std.FirstName)) { updatestd.FirstName = std.FirstName; }
if (!string.IsNullOrWhiteSpace(std.LastName)) { updatestd.LastName = std.LastName; }
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
and here you can see ajax code
<button class='upbtn' data-upid=" + stdid + ">Update</button>
$(".upbtn").click(function () {
var student = {
"upFirstName" : $("#name").val(),
"upLastName" : $("#lname").val(),
}
$.ajax({
url: "/AjaxStudent/UpdateStudent",
method: "Post",
data: {
idtoSearch: upid,
std: student
}
}).done(function(){
alert("Update button");
}).
error(function () {
alert("Update Error");
});
});
I am unable to get any update at browser. Anybody please tell me what should I do.
I have solved my problem. I was updating my data in wrong variable i.e. upFirstName
& upLastName
. That was my mistake. I should update my data in same variable i.e. FirstName
& LastName
. Just write below code
var student = {
"FirstName" : $("#name").val(),
"LastName" : $("#lname").val(),
}
Instead of this
var student = {
"upFirstName" : $("#name").val(),
"upLastName" : $("#lname").val(),
}
I hope it's will be helpful for you also.