简体   繁体   中英

Implement JQuery in ASP.NET Core MVC V2 Partial View

I am loading a partial view from ASP.Net Core MVC V2 controller.

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 --

@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.

Most likely the reason for your code not working is because the document.ready() is not fired. The syntax you are using:

$(function() {

})

is shortcut for $(document ).ready()

In your case, you are simply loading a fragment of HTML/Script from the backend and populating the "partialViewDiv" element. 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.

Removing the following lines solved my problem-

@section Scripts{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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