Reputation: 1363
How can one call a javascript function in html.actionlink in asp.net mvc?
I want to call one method, which is in JavaScript, but how I call it within html.actionlink in the same page?
Upvotes: 37
Views: 166852
Reputation: 96
This is a bit of an old post, but there is actually a way to do an onclick operator that calls a function instead of going anywhere in ASP.NET
helper.ActionLink("Choose", null, null, null,
new {@onclick = "Locations.Choose(" + location.Id + ")", @href="#"})
If you specify empty quotes or the like in the controller/action, it'll likely add a link to what you listed. You can do that, and do a return false in the onclick. You can read more about that at:
What's the effect of adding 'return false' to a click event listener?
If you're doing this onclick in an cshtml file, it'd be a bit cleaner to just specify the link yourself (a href...) instead of having the ActionLink handle it. If you're doing an HtmlHelper, like my example above is coming from, then I'd argue that calling ActionLink is an okay solution, or potentially better, is to use tagbuilder instead.
Upvotes: 4
Reputation: 374
This is the only one that worked for me in .cshtml file:
@Html.ActionLink(
"Name",
"Action",
"Controller",
routeValues: null,
htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})
I hope this helps.
Upvotes: 1
Reputation: 9776
<a onclick="MyFunc()">blabla..</a>
There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.
Upvotes: 9
Reputation: 747
For calling javascript in your action link you simply need to write actionlink like this:
@Html.ActionLink("Delete", "Your-Action", new { id = item.id },
new { onclick="return confirm('Are you sure?');"})
Don't get confused between route values and the html attributes.
Upvotes: 27
Reputation: 747
@Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})
Upvotes: 5
Reputation: 37378
you need to use the htmlAttributes anonymous object, like this:
<%= Html.ActionLink("linky", "action", "controller", new { onclick = "someFunction();"}) %>
you could also give it an id an attach to it with jquery/whatever, like this:
<%= Html.ActionLink("linky", "action", "controller", new { id = "myLink" }) %>
$('#myLink').click(function() { /* bla */ });
Upvotes: 68