Search code examples
c#asp.net-coreasp.net-core-mvcrazor-pages

Scripts do not work in my ASP.NET Core view


Scripts in view do not work for me. But at the same time scripts work in _Layout. For example, if I add a button to _Layout, the script works, but in the same view the same button does not work.

I tried to do it through

@section Scripts { code... }

@RenderSection("Scripts", required: false)

but it doesn't work at all in both _Layout and view

Update :

Where it is highlighted in yellow, this button is located in _Layout, and where it is red, it is located in View. Yellow invokes the script without issue. And red does not cause

enter image description here


Solution

  • Please make sure the value of id attribute must be unique within the DOM, you can specify different value for these two cart button, like below.

    <button id="btnCrt1">Cart</button>
    
    <button id="btnCrt2">Cart</button>
    

    Then use following selector to select/match element(s) that have the id attribute with a value beginning exactly with btnCrt.

    $("button[id^='btnCrt']").click(function () {
        //code logic here
    })