简体   繁体   中英

Click event not firing on link generated with Html.ActionLink

I have an ActionLink as below:

@Html.ActionLink("-Pg", "SupprimerPage", "Section", 
new { pageId = @item.Id }, new { @id = "ConfirmDeletePage", @class = "editLink", style 
= "width:30px" })

And my script:

  $(document).ready(function () {
    $(document).on('click', '#ConfirmDeletePage', function () {
        var x=confirm("Confirm delete page?");
        console.log(x);
        if (x == true){
            return true;
        }
        else {
            return false;
        }
    });
});

When I use a hardcoded link with the <a> tag, it works fine. But when I try to generate the link using Html.ActionLink , the event handler is not called. any help?

For your problem "when I click on Yes, the method in the ActionLink is not being called" this is because you are returning yes on yes button so after execute your function it follow link "href" that's why it seems the method in the ActionLink is not being called, just return false or use event.preventDefault(); inside of true section which run on press yes button

  $(document).ready(function () { $(document).on('click', '.editLink', function (event) { var x=confirm("Confirm delete page?"); console.log(x); if (x == true){ return true; } else { alert('Pressed NO') return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <a href="http://hello.com" class="editLink" >Click me !</a> 

for more go with this anchor-tag-with-javascript-onclick-event

If it works with a hardcoded link, but not when you use an ActionLink, that means the ActionLink must be generating something different to your hardcoded link, which means your jQuery selector ( #ConfirmDeletePage ) is not finding the element.

You can confirm this by using your browser's developer tools to inspect the <a... tag generated by the ActionLink.

Based on the question Html.ActionLink with a specified HTML id maybe you need to change @id = "ConfirmDeletePage" to id = "ConfirmDeletePage" .

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