首页 > 解决方案 > 为什么单击按钮时我的局部视图没有呈现?

问题描述

目标是加载部分视图而不刷新整个页面,只刷新部分视图本身,当我这样做时,我希望我传递给视图的模型 int增加。

但是当我尝试通过按下按钮来加载视图时,它会说..

XML Parsing Error: no root element found Location in Console

这很有趣,因为在控制台中它也输出

<h1>Hello from _Items partial view. + 1</h1>

这是我的 index.cshtml

<button class="btn btn-primary" onclick="LoadInfo()">Load</button>
<div class="text-center">

</div>


<script>
    function LoadInfo() {

        $.ajax({
            url: "Home/LoadView",
            type: 'GET',
            success: function (response) {
                console.log("Did it get called is the question..");
                console.log("Response: " + response);
                $(".text-center").load(response);
            }
        });
    }
</script>

和局部视图

@model int

<h1>Hello from _Items partial view. + @Model</h1>

以及控制器

int i = 0;
[HttpGet]
public IActionResult LoadView()
{
    i++;
    return PartialView("_Items", i);
}

标签: jqueryasp.netajaxasp.net-mvcasp.net-core

解决方案


使用以下:

 $.ajax({
            url: "Home/LoadView",
            type: 'GET',
            success: function (response) {
                console.log("Did it get called is the question..");
                console.log("Response: " + response);
                $(".text-center").html(response);
            }
        });

load() 方法从服务器加载数据,即,如果您想从任何文件加载数据,则可以使用 load()。但是当您从部分视图中获取数据时,部分视图会返回 HTML 文档,您需要将其添加到选定的 div 中。因此,每当您使用局部视图时,请尽量避免使用 load()。


推荐阅读