how to call javascript function in html.actionlink in asp.net mvc?
i wan to call one method which is in java script but how to call it within html.actionlink in same page thanks in advance
This question is related to
javascript
asp.net
asp.net-mvc
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 */ });
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.
@Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})
<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.
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.
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.
Source: Stackoverflow.com