Can't Update Partial View With Ajax ASP.NET Core MVC

三世轮回 提交于 2019-12-08 09:31:08

问题


I want to update my partial View with Ajax, but for some reason, it doesn't work. If I use load method (and comment ajax code), it works. this is my code:

this is my main View:

@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 })');*@

});

this is my question action method int Test controller:

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

what mistake do I have?


回答1:


You have specified dataType: "json", but your method returns a view (html), not JsonResult so an exception is being thrown.

Either omit the dataType option (the function will work it out based on the response) or change it to dataType: 'html'

In addition, your can delete the contentType option. You are making a GET which has no body so its ignored (and if it was a POST, your method would also fail because you have not stringified the data).

Your url should also be /Test/Question (leading forward slash), and you should always use the @Url.Action() method to generate the url

Your function should be

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


来源:https://stackoverflow.com/questions/51114427/cant-update-partial-view-with-ajax-asp-net-core-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!