Update Record by using ajax in Entity Framework MVC

ajax asp.net-ajax asp.net-mvc entity-framework-4 entity-framework-6

Question

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

AjaxStudentController

[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.

1
2
7/8/2018 4:06:16 PM

Popular Answer

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.

3
7/9/2018 8:35:57 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow