使用 Ajax 调用将 div 替换为部分视图无效

Replacing div with Partial View using Ajax Call Not working

所以我有一个 5 星评级系统,每颗星都调用这个函数:

function Test(ideaId, rating){
    //alert(ideaId + " : " + rating);
    $.ajax({
        url: '@Url.Action("RateIdea", "Ideas")',
        dataType: "json",
        type: "Get",
        data: { "ideaId": ideaId, "ratingValue": rating, "challengeId": @Model.pkiChallengeId }
    }).done(function (response) {
        //alert('test');
        $("#divDetailsPartial").html(response);
    });
}

被呼叫的ActionResult

public ActionResult RateIdea(int ideaId, int ratingValue, int challengeId)
{
    string loggedInUserId = User.Identity.GetUserId();

    int id = clsIdeas.SaveRating(ideaId, ratingValue, loggedInUserId);

    ChallengeIdeasViewModel CIVM = new ChallengeIdeasViewModel();
    IEnumerable<Ideas> ideasList;

    CIVM.ideasList = clsIdeas.GetChallengeIdeas(challengeId, loggedInUserId);
    CIVM.ChallengeStatus = clsIdeas.GetChallengeStatus(challengeId);

    return PartialView("Details", CIVM);

    //return Json(new { status = "success" }, JsonRequestBehavior.AllowGet);
}

在我的 View:

<div class="widget-body no-padding">
    <div id="divDetailsPartial">
          @Html.Action("Details", "Ideas", new { id = Model.pkiChallengeId })
   </div>

</div>

解释一下,当页面加载并显示包含 table 数据的部分视图时,将调用该操作。我的评级系统有效(数据库已更新),我只想刷新相同的部分视图,而不必刷新整个页面。

如果我 return 一个 JSON 结果并且只显示一个警告,它会起作用,但当我想用局部视图替换 div 时就不行了。

我错过了什么?

因为您指定您的 ajax 调用期望从服务器返回 json 结果,而您从 action 方法返回 PartialView 将作为 html 字符串从服务器返回。

因此更改以下行:

dataType: "json"

要么删除上面的行,要么调整它以告知它 html 从服务器返回。

以下设置将告诉它它期望返回 html 结果:

dataType : "html"

在此处阅读有关 dataType attribue in ajax call

的信息