nam nam - 4 months ago 18
jQuery Question

How to add a jQuery code on a specific page only

In my ASP.NET Core Code first project developed using

ASP.NET Cor Web Application (.NET Core) template
how can I add, for example, following jQery code on a specific view, say,
test.cshtml
so that it is included only on a page using this view. I'm using
VS2015-Update3.1
. Only those familiar with the folder structure of such a project in VS2015 can probably answer.

NOTE: I'm trying to add following script inline and not as a file.

$('.list-group-item').click(function(e){
e.stopPropagation();
})

Answer

The standard _Layout.cshtml file that comes with the standard project template calls RenderSection() near the very bottom:

@RenderSection("scripts", required: false)

This tells the ViewEngine to insert a section called scripts (if present) from the rendered View (which gets inserted exactly in the place where RenderBody() is called.

// Test.cshtml

...
<ul class="list-group">
  <li class="list-group-item">Item-1</li>
  <li class="list-group-item">Item-2</li>
  <li class="list-group-item">Item-3</li>
</ul>
...

@section scripts
{
  <script>
    $('.list-group-item').click(function(e){ 
      e.stopPropagation();
    })
  </script>
}

So just define the section in your view and it will get inserted in the layout in the designated place.