Calling jQuery function on external page from html.actionlink

Viewed 141

I have an action link like this:

@html.actionlink("link", "action", "controller", new { id = item.id }

I want this link to call a jQuery function on an external page. I have tried with onclick but it always goes to the default controller action method and so does for @class.

I would like to know can I use it like this:

@html.actionlink("link text", null, null, new { id = item.id }, new { onclick = "myfunction() }

This still does not call the jQuery function, what am I doing wrong?

here is my html hyperlink

@item.ProductID.ToString()

and below is my jquery script locate in an external js file

$(document).ready({
function showdetails(id)
{
alert("you clicked me")
});
1 Answers

If you just want to make it run a jQuery function and not go to a controller then there's no point using the actionLink helper - the whole purpose of that is to generate a hyperlink with the correct URL to the action method. Instead, just write a HTML link (or button) directly and attach the click event to it. There's no need to us any Razor code.

Something like this:

<button type="button" class="linkbutton" onclick="myfunction(@item.id)">Click here</button>

The other mistake is to put the function within a $(document).ready({ block. It's unnecessary because the idea of that block is only to stop code executing before the page has finished loading. With a function, which is only called from other code, not executed immediately, you don't have that worry. And it causes the error because it means that your function only has scope within that block. It isn't accessible to code outside the block.

Demo:

function myfunction(x)
{
  alert(x);
}
.linkbutton
{
  border: none;
  background: none;
  color: blue;
  text-decoration:underline;
}

.linkbutton:hover
{
  cursor:pointer;
}
<button type="button" class="linkbutton" onclick="myfunction(3)">Click here</button>

Related