ajax - 无法使用 Ajax ASP.NET Core MVC 更新部分视图
问题描述
我想用 Ajax 更新我的部分视图,但由于某种原因,它不起作用。如果我使用加载方法(并注释 ajax 代码),它可以工作。这是我的代码:
这是我的主要观点:
@model IEnumerable<WebApplicationMVC.Models.Test>
@{
ViewData["Title"] = "Testing";
}
<div id="partial">
@await Html.PartialAsync("Question", Model.ToList()[0])
</div>
<input type="button" id="b" value="next" class="btn btn-default" />
<script>
$("#b").click(function () {
//this code doesn't work
$.ajax({
url: 'Test/Question',
type: 'GET',
contentType: "application/json; charset=utf-8",
data: { id: '@Model.ToList()[1].ID' },
dataType: "json",
success: function (result) {
$("#partial").html(result);
}
});
//this code works
@*$("#partial").load('@Url.Action("Question","Test",new { id=Model.ToList()[1].ID })');*@
});
这是我的问题操作方法 int测试控制器:
public IActionResult Question(int id)
{
return View(Methods.GetTestById(id));
}
我有什么错误?
解决方案
您已指定dataType: "json",
但您的方法返回一个视图(html),而不是 JsonResult
抛出异常。
要么省略该dataType
选项(该函数将根据响应解决)或将其更改为dataType: 'html'
此外,您可以删除该contentType
选项。您正在制作一个没有正文的 GET,因此它被忽略(如果它是一个 POST,您的方法也会失败,因为您没有对数据进行字符串化)。
您的 url 也应该是/Test/Question
(前导斜杠),并且您应该始终使用该@Url.Action()
方法生成 url
你的功能应该是
$.ajax({
url: '@Url.Action("Question","Test")',
type: 'GET',
data: { id: '@Model.ToList()[1].ID' },
success: function (result) {
$("#partial").html(result);
}
});
推荐阅读
- reactjs - 如何防止 ReactSelect 清除输入?
- html - 如何制作响应性崩溃的边距?
- docker - 尝试连接到 EC2 上的 docker 容器时连接被拒绝
- windows-subsystem-for-linux - 在 WSL2 上的 Ubuntu 上运行 nessu
- python - 关于 PyCharm IDE 中包管理的问题
- html - 移动设备:使用 css 获取屏幕区域大小和位置,而不仅仅是视口
- android - 如何使用 Firebase Firestore 加载更多数据“.startAfter(lastVisible)” - 使用 Kotlin 的 Android Studio
- visual-studio-code - 部署到 Azure 扩展 - 仅允许创建 Github 操作工作流。不允许 GitHub + Azure Pipelines 流创建
- mediawiki - 如何美化/美化 wiki 标记?
- security - 如果我不能将它推送到 github,我的配置应该保存在哪里?