rem
rem

Reputation: 85

Update partial view using Ajax not working

Experimenting with partial views in MVC 5, can't refresh my partial view using Ajax on button click:

This is my partial view:

@model dbsapplication.Models.CarRepository

   @{
        Layout = null;
   }

@Html.DisplayFor(model => model.Engine)

in my Index page, I have:

<div id="@car.ID">
       @Html.Partial("PartialView", car)
</div>

and my button:

<button onclick="loadProject(@car.ID)">Car ID: @car.ID</button>

My Ajax call:

<script>
function loadProject(car_ID) {
//alert('#' + car_ID);
    $.ajax({
        type: "GET",
        url: '/Home/partialView/',
        data: { id: car_ID },            
        async: true,
        cache: false,
        dataType: "html",
        success: function (data) {
            $('#' + car_ID).empty();
            $('#' + car_ID).html(data);
            alert("Updated!");
            },
        });
    }
</script>

my controller:

public PartialViewResult partialView(int id)
{
   CarRepository car = new CarRepository();
   car.updateCar_partial(id);
   return PartialView("PartialView", car);
}

car.updateCar_partial(id);

This method simply sets the Engine for a given car back to default value which is ("Not specififed"). When I click the button, the ajax call runs and the alert is triggered but the DIV the data is meant to load into goes blank. Only when I refresh the page, the partial view is updated to the correct value.

Refreshed via F5 or when I add location.reload which i think defeats the purpose as this reloads the whole page not the div.

Not sure if what i'm doing is possible, any help would be appreciated.

Other question I have to try and fix:

Update Partial View Within Partial View Using MVC Ajax AJAX not updating partial view

Upvotes: 0

Views: 1310

Answers (1)

hasan
hasan

Reputation: 3502

I would suggest to use jquery load() function to fill partial view into your target html element like following.

function loadProject(car_ID) {

     var url = '@Url.Action("partialView", "Home")' + "?id=" + car_ID;
     var targetElement = $("#" + car_ID);

     targetElement.load(url, function(responseTxt, statusTxt, xhr){
         if(statusTxt == "success")
         console.log("It worked");
     })
}

Upvotes: 0

Related Questions