简体   繁体   English

在ASP.NET Core MVC V2局部视图中实现JQuery

[英]Implement JQuery in ASP.NET Core MVC V2 Partial View

I am loading a partial view from ASP.Net Core MVC V2 controller. 我正在从ASP.Net Core MVC V2控制器加载局部视图。

Client side- 客户端-

$.ajax({
   url: url,
   method: 'get',
   contentType: "application/json; charset=utf-8",
   dataType: "html",
   success: function (response) {
                partialViewDiv.html(response);
            }
 });

Server side- 服务器端-

public PartialViewResult UsingManualInput()
{
   return PartialView();
}

Everything is good so far. 到目前为止一切都很好。 But my JQuery code in that partial view is not working -- 但是我在该局部视图中的JQuery代码不起作用-

@section Scripts{
<script>   
    $(function () {
        alert('Hello'); //Not working

        $(document).on('click', '#Button', function () {
            alert('hello'); //Not working
        });
    });
 </script>
 }

Any way to do it? 有办法吗?

It is not clear at what point your AJAX call to load script is triggered. 目前尚不清楚您的AJAX调用加载脚本在何时触发。

Most likely the reason for your code not working is because the document.ready() is not fired. 您的代码无法正常工作的最可能原因是未触发document.ready()。 The syntax you are using: 您使用的语法:

$(function() {

})

is shortcut for $(document ).ready() $(document).ready()的快捷方式

In your case, you are simply loading a fragment of HTML/Script from the backend and populating the "partialViewDiv" element. 就您而言,您只是从后端加载HTML / Script片段,并填充“ partialViewDiv”元素。 The document.ready would not be fired at this time - in all possibility it would have fired even before your ajax call to load the back end script is called. 此时将不会触发document.ready,即使在您的ajax调用加载后端脚本之前,也有可能触发了document.ready。

Removing the following lines solved my problem- 删除以下行解决了我的问题-

@section Scripts{

}

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

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