使用 jQuery ajax 调用在 MVC 视图中绑定部分视图

Bind partial view in MVC View using jQuery ajax call

I have a View as shown below

**<div id = 123 class ="Country">**
  <div class = "content">
      **<need to load partial view here>**
  </div>
**</div>**

**<div id = 234 class ="Country">**
 <div class = "content">
     **<need to load partial view here>**
  </div>

**</div>**
...
...More div's here
...
so on clicking the Country div, i need to load its inner div "content". My jQuery ajax call is like below

    $(".country").on('click', function () {
         $.ajax({
                    url: '@(Url.Action("FilesByCountry", "RelatedFiles"))', //Cont & ActionResult
                    type: "GET",
                    data: $(this).attr('id'), //getting the click id
                    contentType: "application/json; charset=utf-8",
                    success: successFunc,
                    error: errorFunc
                });

            function successFunc(data) {
                **$(this).attr('id').children($('#content', data).html())**
                }

                function errorFunc(xhr, errorType, exception) {
                    alert(xhr.status +  ": " + exception);
                }
        });
    });

所以控制器运行良好,它在调试模式下通过了 PartialView。但是局部视图在主视图中没有约束力。对此有什么想法吗?

我认为这是你填充内容的方式:

$(this).find('.content').html(data);

我认为 #content 用于 ID 选择器,.content 用于 class 选择器。

另一种尝试是只填充一个已知的 div -->

$('#234').find('.content').html(data);

$('#234').html(data);

然后使用开发工具 F12 检查元素,看看里面放了什么。

此外,请确保您正在注入 html 片段。您可以检查 <head><body> 标签的数据,我相信它们不应该存在于您正在做的事情中。

我找到了这个问题的答案。实际上 $(this) 在我的 successFunc 中不起作用并且总是返回 null 。所以我将 Javascript 代码修改为如下内容。

$(".country").on('click', function () {
var _this = $(this);
         $.ajax({
                    url: '@(Url.Action("FilesByCountry", "RelatedFiles"))', //Cont & ActionResult
                    type: "GET",
                    data: $(this).attr('id'), //getting the click id
                    contentType: "application/json; charset=utf-8",
                    success: successFunc,
                    error: errorFunc
                });

            function successFunc(data) {
                _this.find('.content').html(data);
                }

                function errorFunc(xhr, errorType, exception) {
                    alert(xhr.status +  ": " + exception);
                }
        });
    });