I have a control that features code similar to the following:
Javascript
$("#Postcode").autocomplete({
source: '@(Url.Action("AutocompleteHelper"))'
});
HTML
@Html.EditorFor(model => model.Postcode)
It used to all sit directly inside a .cshtml file and Url.Action
generated a working URL as expected.
Recently I needed to use this in a number of views, so I moved the JS into a separate .js file (wrapped into a ScriptBundle
and included in the parent view via @Scripts.Render
) and the corresponding HTML is now rendered as a partial view.
A side-effect of this is that the Razor transformation no longer occurs. I'd prefer not to replace Url.Action
with a hardcoded /<Controller>/AutocompleteHelper string, so is there any other way I can dynamically generate and set this value? I could move the Javascript out of the bundle and into the partial view, but the consensus seems to be that you shouldn't have JS in a partial view.
No, you can't. Javascript files aren't handled by the Razor engine.
You can create a
cshtml
'View' and put the code in there and include it using this code in your page, like I think you did (you don't need an action for this):This way, it will pass the Razor engine and your are set. Unfortunately you can't include it in a bundle then.
Another option is to declare only that variable in the page, and use that inside the javascript that remains 'as is'.