繁体   English   中英

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

所以 controller 运行良好,它在调试模式下通过了 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);
                }
        });
    });

暂无
暂无

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

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