简体   繁体   English

使用Ajax更新部分视图不起作用

[英]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: 在MVC 5中试验部分视图,无法在单击按钮时使用Ajax刷新我的部分视图:

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: 我的Ajax电话:

<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); 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. 当我单击该按钮时,ajax调用将运行并触发警报,但是要加载到数据中的DIV变为空白。 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. 通过F5刷新或当我添加location.reload时,我认为这样做失败了,因为这会重新加载整个页面而不是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 使用MVC Ajax更新部分视图内的部分视图 AJAX不更新部分视图

I would suggest to use jquery load() function to fill partial view into your target html element like following. 我建议使用jquery load()函数将部分视图填充到目标html元素中,如下所示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM