3

This may have already been answered somewhere but I cannot find any information that makes sense to me.

I have a Cancel button in my cshtml that contains a href='@Url.Action("Index"). It looks like this:

<a href='@Url.Action("Index")' class="linkbutton" id="btnCancel" title="Return to Home Page">Cancel</a>

Now, if changes have been made, I need to confirm whether to leave the page or save changes before leaving.

So, I've added an event on the button click to present a popup to confirm to continue or save. Of course, leaving the button code in the cshtml file as it is, acts exactly as one would expect. It's a link and my event never fires.

I changed the cshtml button to the following code:

<input type="button" class="navigationButtons" id="btnCancel" value="Cancel" title="Return to Home Page" />

Now, my event gets fired and I display my popup to confirm continue or save. The save works great because it's another method that performs a save to the db. I can't make the Confirm button into a link button, because it is used in another place in the code that just continues without leaving the page.

I have found answers for window.location, $.get and $.ajax. But I cannot figure out how to put into the JavaScript code that will go to my Index page.

PLEASE! Does anyone know how to do this and help me understand what I obviously do not know. :-(

1
  • 1
    Just handle the links .click() event, display your popup, and if its cancelled, then cancel the default action of the link Commented Oct 12, 2017 at 22:33

1 Answer 1

2

Provided that your JavaScript is included in your .cshtml file, you can write Razor code inside your script:

window.location.replace('@Url.Action("Index")');

If you're having trouble with that, you could try creating a hidden link on your page and having your JavaScript trigger a click:

<a id="my-hidden-url" href="@Url.Action("Index")" hidden></a>

<script>
    $('#my-hidden-url').trigger('click');
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

The JavaScript is a separate file. I'm not sure this will work for me unless I change my strategy.
If you want to keep your JS separate, you don't have to use the Url Helper. If you're confident that the URL will stay stable, you could hardcode it in the replace() function.
Perhaps I need to learn how to use window.location.replace, because it's doing the same thing everything else I tried. Nothing! I'm looking into it. :-\
@Patricia I've edited my answer to include an extra solution that could also solve your issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.