How do I code the equivalent of an @Html.ActionLink through javascript code i.e. call an MVC action which will then create a new View without coming back to the calling view?
How do I code the equivalent of an @Html.ActionLink through javascript code i.e. call
Share
javascriptis a client side language which doesn’t know anything about the server side language you are using. Thus it is normal that there’s no equivalent in javascript of the server side helper that generates an url using your server side route definitions.It is not quite clear what you are trying to achieve but if you want to use call some url through javascript you could generate this url using a server side helper:
If you want to use this url in a separate javascript file where you don’t have access to server side helpers you could still, depending on the situation, include this url in some DOM element.
For example:
Notice the
data-urlHTML5 attribute that we have embedded into the DOM and used a server side helper to ensure that the generated url will always be correct based on our routing definitions. Now we could in a separate javascript file unobtrusively subscribe to the click event of this div and retrieve the url:Other examples obviously include the standard
<a>and<form>elements which should be generated using server side HTML helpers and then all you have to do in your separate javascript file is to fetch their correspondinghreforactionattributes to retrieve the actual url and do something with it.