1

I have a page that is rendered via an ActionResult called EntityIndex that takes int id as a parameter and loads that entity.

On this view a user can select from a dropdown other related entities and the view should reload by sending the selected ID from the dropdown to the same Action EntityIndex with the new ID.

I'm using a jQuery change event on the dropdown to navigate and reload the page:

$("#RelatedEntity").change(function () {
    window.location = '@Url.Action("EntityIndex", new {id = ""})' + '/' + $(this).val();
});

This is the Action

public ActionResult EntityIndex(int id) {
    ... gets entity by id here ...
    return View(model);
}

The action works fine when hit but the jQuery line above is failing with an error:

http://localhost:1798/Entity/EntityIndex/@Url.Action("EntityIndex", new {id = ""})/539

For some reason the window.location firing the @Url.Action is treating the action as a string and not an action to navigate to... what is wrong with the Url.Action that keeps it from behaving correctly?

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
CD Smith
  • 6,597
  • 7
  • 40
  • 66

1 Answers1

5

Your JQuery is ever-so-slightly off. Using the default route and specifying no ID will generate:

/controller/action/

So all you need to do is put your value on the end. Try this:

$("#RelatedEntity").change(function () {
    window.location = '@Url.Action("EntityIndex")' + $(this).val();
});

Should give you (assuming value is 23):

/controller/action/23

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • Unfortunately, that did not work, using that I navigate to http://localhost:1798/Entity/EntityIndex/@Url.Action(%22EntityIndex%22)539 which doesn't give me the big ugly IIS error that I was getting, but more of a 'what the hell is this string parameter?' type error – CD Smith May 22 '12 at 16:56
  • Ah hang on, are you trying to use this in an external JS file or something other than a Razor view? – Mathew Thompson May 22 '12 at 16:58
  • Yes! This JS is in a separate file Entity.js and is inside the document.ready section and is referenced into the view with the script tag – CD Smith May 22 '12 at 16:59
  • 5
    Ah then you can't use Razor syntax in an external file, what you'll have to do is either store the Razor generated link inside a hidden input OR call a function in your external JS file from your view and pass it the Razor generated link as a parameter to the function, then store that globally in a variable in your JS file. Using `@URl....` in a JS file is literally just using a string with the @ in :) – Mathew Thompson May 22 '12 at 17:01
  • Hahahaha don't worry, happens to the best of us :). I'm sure I've tried and failed that before! – Mathew Thompson May 22 '12 at 17:03
  • Thanks, I put it back inside my partial (new partial form where it was before - that's the reason why I moved it to begin with) works like a charm with original code now :-) – CD Smith May 22 '12 at 17:07