Search code examples
jqueryajaxasp.net-mvcpartial-views

Replacing div with Partial View using Ajax Call Not working


So I have a 5 star rating system, and each star calls this function:

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);
    });
}

The ActionResult being called:

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);
}

In my View:

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

</div>

To explain, the Action is called when the page loads and displays a partial view with a table of data. My rating system works(DB is updated), and I just want to refresh this same partial view without having to refresh the whole page.

If I return a JSON result and just display an alert, it works, but not when I want to replace a div with the partial view.

What am I missing ?


Solution

  • Because you are specifying that your ajax call expects json result back from server while you are returning PartialView from action method which will be returned as html string from server.

    So change the following line:

    dataType: "json"
    

    either remove the above line or adjust it to tell that it epxects html back from server.

    The following settings will tell it that it expects html result back:

    dataType : "html"
    

    Read here about the dataType attribue in ajax call