JQuery 函数只是在第一次按下提交按钮时调用控制器操作

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

本文关键字:按钮 提交 调用 操作 控制器 函数 第一次 JQuery      更新时间:2023-09-26

我有一个名为InsertShowStudents()的JQuery函数,每次按下提交按钮()时都会正确执行。成功后,我将调用另一个函数GetStudents()以显示表中元素的更新列表。GetStudents()函数只是在第一次按下按钮时调用控制器操作。之后,InsertShowStudents()继续在表中插入,但GetStudents()函数不会调用控制器上的操作方法。我用断点来证明它,你知道发生了什么吗??

JQuery 代码:

$(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)
    })
}

控制器操作:

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);
}

在这种情况下,第一次工作,我会假设缓存问题。 要强制绕过缓存,您可以将该选项添加到 ajax 请求中。 有关更多信息,请查看 jquery ajax 文档

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

试试这个

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