Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC equivalent of @Html.ActionLink through javascript

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?

like image 384
Martin Avatar asked Jun 11 '12 16:06

Martin


People also ask

What is HTML ActionLink in mvc?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

How do I pass an HTML model in ActionLink?

The Lookup method's arguments match the named properties in the ActionLink. MVC4 allows you to pass the model automatically through URL variables, which is seen my second example. The docs for ActionLink show that none of that method's overloads accepts a viewmodel object.

Can ASP NET MVC use JavaScript?

JavaScript can be used in asp.net mvc. If you go for Asp.NET Web forms, there is no need to have a detailed understanding of HTML, CSS or JavaScript as it abstracts all these details and provides automatic plumbing.


1 Answers

javascript is 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:

<script type="text/javascript">
    var url = '@Url.Action("SomeAction", "SomeController")';
    // do something with the url client side variable, for example redirect
    window.location.href = url;
</script>

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:

<div id="foo" data-url="@Url.Action("SomeAction", "SomeController")">Click me</div>

Notice the data-url HTML5 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:

$('#foo').click(function() {
    var url = $(this).data('url');
    // do something with the url client side variable, for example redirect
    window.location.href = 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 corresponding href or action attributes to retrieve the actual url and do something with it.

like image 181
Darin Dimitrov Avatar answered Nov 15 '22 21:11

Darin Dimitrov