Ajax帖子无法使用MVC 5
本文关键字:MVC Ajax | 更新日期: 2023-09-27 18:25:36
我试图将数据发布到控制器中,但似乎不起作用,我需要在完成后将视图的内容包含到div中,但我无法完全实现
这是我的js函数:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: "Student/Schedule",
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').load(a);
}
});
}
这是我的控制器:
public ActionResult Schedule(String number)
{
return View(number);
}
我是MVC和C#的新手,所以欢迎任何帮助。
您应该修复一些东西来解决问题。
-
将Url更改为
"/Student/Schedule"
您正在使用
"Student/Schedule"
作为url,因此您正在尝试调用名为"Student"的操作。 -
将
[HttpPost]
添加到您的操作中。 -
你应该
return PartialView("Schedule", number);
。当您使用
return View(number)
时,它会使用数字的字符串值作为视图名称。您应该显式传递视图名称和模型。 - 使用
$('#schedule').html(a);
最好在ajax调用中添加一个错误函数,以便能够查找错误:
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
//or you can put jqXHR.responseText somewhere as complete response. Its html.
}
您的操作应该返回Partial View,而不是View。
将您的操作更改为:
[HttpPost]
// by the way use string instead of String
public ActionResult Schedule(string number)
{
return PartialView("_Schedule", number);
}
然后,您需要创建一个名为_Schedule.cshtml
的局部视图。
此外,您需要将$('#schedule').load(a);
更改为$('#schedule').html(a);
。我建议您在ajax调用中使用Url.Action
来设置url,如下所示:
function show(num) {
$.ajax({
dataType: "html",
type: "POST",
url: '@Url.Action("Schedule", "Student")',
data: { number: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#schedule').html(a);
}
});
}
我遇到了同样的问题,我所做的是将jquery.uno唐突-ajax.js添加到我的脚本