首页 > 解决方案 > 无法使用 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));
}

我有什么错误?

标签: ajaxasp.net-core-mvc

解决方案


您已指定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);
    }
});

推荐阅读