JQuery 函数只是在第一次按下提交按钮时调用控制器操作
JQuery function just call controller action the first time submit button is pressed
我有一个名为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)
})
}
相关文章:
- 使用按钮和单选按钮提交表单,但始终使用相同的值
- 使用回车按钮提交文本框表单
- 清除按钮提交后的文本区域
- 单击按钮提交输入字段值
- 我可以从 Rails 4 中的按钮提交传递参数吗?
- 如何使用inputtype=按钮提交表单
- 使用两个按钮(提交按钮和普通按钮),它们应该以不同的方式提交相同的表单
- 使用jquery UI next按钮提交输入字段值,php将返回结果
- AJAX-按钮提交以更新表单
- 在向导表单中使用按钮提交值的最佳方式
- 如何阻止按钮提交
- 使用提交按钮提交表单,而不是页面上的其他按钮
- 用于两个功能的Javascript按钮.提交&单击
- 如何使用一个提交按钮提交三个表单
- 如何使用按钮提交表单
- 如何查看从 javascript 中的表单按钮提交调用的 php 文件中的回显
- 不能在按钮提交处理程序中使用变量
- 由多个按钮提交的一个模式引导表单
- 为什么<输入类型=“按钮”>提交表单
- 使用表单外的按钮提交表单