AlexGH AlexGH - 4 months ago 40
jQuery Question

JQuery function just call controller action the first time submit button is pressed

I have a JQuery function called

InsertShowStudents()
which is executed correctly every time a submit button() is pressed. On success, I'm calling the other function
GetStudents()
to show the updated list of elements in the table. The
GetStudents()
function just calls the controller action the first time the button is pressed. After that,
InsertShowStudents()
continues inserting in the table but the
GetStudents()
function doesn't invoke the Action Method on the controller.. I've used a breakpoint to prove it, do you know what's happening??

JQuery code:

$(function () {
$("#btnInsertStudent").click(function () {
InsertShowStudents();
return false;
})

})

function InsertShowStudents() {
$.ajax({
type:"post",
url: "/Students/InsertStudent/",
data: { Name: $("#Name").val(), LastName: $("#LastName").val(), Age: $("#Age").val() }
}).success(function () {
GetStudents();
//clear the form
$("#myform")[0].reset();
}).error(function () {
$("#divGetStudents").html("An error occurred")
})
}

function GetStudents()
{
$.ajax({
type: "get",
url: "/Students/GetStudents"
}).success(function (result) {
$("#divGetStudents").html(result)
})
}


Controller Actions:

public ActionResult InsertStudent()
{
return View();
}

[HttpPost]
//[ValidateAntiForgeryToken]
public ActionResult InsertStudent(Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return View();
}
return View(student);
}

public PartialViewResult GetStudents()
{
List<Student> students = db.Students.ToList();
return PartialView(students);
}

Answer

In a situation like this where the first time is working I'd assume a cache problem. To force bypass the cache you can add the option to the ajax request. For more information check out the jquery ajax documentation

$.ajax({
        type: "get",
        url: "/Students/GetStudents",
        cache: false
    }).success(function (result) {
        $("#divGetStudents").html(result)
    })