jqueryasp.net-core-mvcdom-eventsbuttonclickasp.net-mvc-partialview

PartialView does not work properly when called from Layout.cshtml


enter image description here - issue added as it stack overflow is not accepting the code

i am trying to call a partial view(there is a button on the click of which i should be able to close a div .the div is also present in the partial view )from layout file but its not working.

if i call the partial view in the main page then its working fine.

i have tried all the ways but nothing is working


Solution

  • As normal, partial View is loaded together with the parent view. Therefore, the javascript command should be reside on the parent view rather than the partial view itself.

    When you run your code you can see the below error in Console panel(F12 in the browser to check).

    Uncaught ReferenceError: $ is not defined

    To globally make the partial view's js work for the view which applied the _Layout, you could move the jquery reference to the head section of the _Layout.cshtml page and write your custom js code in partial view.

    <head>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
        //add the jquery reference in the head section....
        <script src="~/lib/jquery/dist/jquery.min.js"></script>    
    </head>