【发布时间】:2021-10-24 14:33:07
【问题描述】:
我正在 MVC 中处理产品目录,我需要将一些 JSON 值从控制器返回到索引页面。它以对控制器操作的 AJAX 调用开始,格式如下:
$('.GetData_Action').click(function (index) {
RememberVerticalScroll();
$.ajax({
url: this.href,
type: 'GET',
success: function (result) {
//categoryID = result.categoryId;
//ShowProducts();
}
});
});
this.href 引用了被点击的原始 ActionLink。 this.href 是需要调用的控制器/动作,包含参数 int categoryID、int level。 ActionLink(也在 Index.cshtml 中)如下所示:
@Html.ActionLink(@item.CategoryName, "GetData", "SimpleMenu", new { categoryID = item.Id, level = level },
new { @class = "GetData_Action" })
单击带有类 GetData_Action 的 ActionLink 后,将调用 jquery 函数 $('.GetData_Action').click 并执行 AJAX GET 请求。
现在,被调用的控制器 Action 应该向 AJAX 调用的成功分支返回两个 JSON 值,如下所示:
[HttpGet]
public JsonResult GetData(int categoryID, int level)
{
string VerticalScrollPosition;
if (Session["VertScrollPos"] != null)
{
VerticalScrollPosition = Session["VertScrollPos"].ToString();
Session["VertScrollPos"] = null; // reset Session
}
else
{
VerticalScrollPosition = null;
}
return Json(new { categoryId = categoryID , VerticalScroll = VerticalScrollPosition }, JsonRequestBehavior.AllowGet);
}
问题如下。当我单击 ActionLink 时,将调用控制器方法并且该方法正确返回 JSON,但随后浏览器会重定向到带有纯 JSON 数据的单独页面(见下图)。相反,控制器应该将 JSON 返回到 AJAX 调用的成功分支,因为我希望能够使用结果。我为 AJAX 调用尝试了许多不同的格式,但它们都没有改变结果。此外,MVC 不接受执行和接收 POST 调用而不是 GET 调用,并导致错误页面提示未找到控制器:在控制器上未找到公共操作方法。
重定向到的纯 JSON 页面:
【问题讨论】:
-
尝试将action的返回类型从JsonResult改为ActionResult。
-
与 ActionResult 的结果相同。我通过 GET 请求获取纯 JSON 数据或通过 POST 请求获取错误页面,
标签: jquery json ajax asp.net-mvc