Search code examples
c#asp.netrazor

asp.net, razorpages: how to put a confirmation box in between actions


I have this URL action:

 <a href="@Url.Action("DeleteCat", "GlobalTagging", new { id = Model.MainNodes[i].Id})">Löschen</a>

this triggers a function in my code behind:

 public ActionResult DeleteCat(int? id) { }

The problem is that I am not able to insert a confirmation dialogue (yes / no) in between. I tried with javascript:

     function DeleteCat(value) {
*ALERT*
           @Url.Action("DeleteCat", "GlobalTagging", new { value})
       }

But the issue is, that I cannot pass the js param to the c# function as they are from different runtimes.

So I need to trigger the alert from the code I guess, but I haven't found any valid solution.

I did come across this:

Response.Write("<script>alert('Data inserted successfully')</script>");

But I wasn't able to inflate a dialogue box with a yes / no option and respond to it. Maybe this code can be altered, so it can be used inside c#?

Any idea is welcome!

Thanks!


Solution

  • You can create a click event either via the onclick attribute of your anchor or by calling youritem.addEventListener('click', redirect);

    function redirect(event) {
        if (!confirm("Are you sure")) event.preventDefault();
    }
    <a href="https://stackoverflow.com" onclick="redirect(event)">Foo</a>

        function redirect(event) {
            if (!confirm("Are you sure")) event.preventDefault();
        }
        document.getElementById("foo").addEventListener('click', redirect);
        <a id="foo" href="https://stackoverflow.com">Foo</a>