【问题标题】:Can't Update Partial View With Ajax ASP.NET Core MVC无法使用 Ajax ASP.NET Core MVC 更新部分视图
【发布时间】:2018-06-30 11:20:02
【问题描述】:

我想用 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 Test 控制器:

public IActionResult Question(int id)
{
    return View(Methods.GetTestById(id));
}

我有什么错误?

【问题讨论】:

    标签: ajax asp.net-core-mvc


    【解决方案1】:

    您已指定 dataType: "json",,但您的方法返回的是视图 (html),而不是 JsonResult,因此会引发异常。

    要么省略dataType 选项(该函数将根据响应解决)或将其更改为dataType: 'html'

    此外,您可以删除contentType 选项。您正在制作一个没有正文的 GET,因此它被忽略(如果它是一个 POST,您的方法也会失败,因为您没有对数据进行字符串化)。

    您的网址也应该是/Test/Question(前导斜杠),并且您应该始终使用@Url.Action() 方法来生成网址

    你的功能应该是

    $.ajax({
        url: '@Url.Action("Question","Test")',
        type: 'GET',
        data: { id: '@Model.ToList()[1].ID' },
        success: function (result) {
            $("#partial").html(result);
        }
    });
    

    【讨论】:

    • 我想补充一点,点击按钮时没有抛出异常
    • 当然会抛出异常(你会得到一个500(Internal Server Error) - 另请注意有关 url 的编辑
    • 你应该学会使用浏览器工具来调试你的代码:) - 不正确的 url 会给出 404 错误,dataType 会给出 500 错误跨度>
    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多