Redirect using Url.Action in JS click handler not working

Viewed 39

Multiple Url.Action() does not work at same time in script. Only the first Url.Action() works. I need to check a condition

$(document).ready(function action() {
  $("#Action").click(function myfunction() {
    if ($('[id="Accessory0"]').is(':checked')) {
      @Url.Action("Submit_Acc", "AccessoryManager");
    } else if ($('[id="Accessory1"]').is(':checked')) {
      @Url.Action("Submit_AccW", "AccessoryManager");
    }
  });
});
1 Answers

The problem is because Url.Action() outputs a string. If you look at the output of your code you will just see the relative path of the Action placed in the JS with no context around it, and this will only cause an error.

To address this you need to call location.assign() providing the output of Url.Action() as an argument, like this:

$(document).ready(function() {
  $("#Action").click(function() {
    if ($('#Accessory0').is(':checked')) {
      window.location.assign('@Url.Action("Submit_Acc", "AccessoryManager")');
    } else if ($('Accessory1').is(':checked')) {
      window.location.assign('@Url.Action("Submit_AccW", "AccessoryManager")');
    }
  });
});

There's a few other things to note here. Firstly when selecting an element by its id, use an id selector not an attribute selector.

Secondly, this solution (and your original code) assumes that the C# logic is placed in a location where it can be interpreted and output to the JS code. Importantly this means that it will not work when used in a .js file. You would need to place it within the .cshtml of your view.

Lastly, you shouldn't provide function names for your anonymous functions. That's why they're called anonymous functions.

Related