Per Källström Per Källström - 4 years ago 773
Javascript Question

Call javascript function in c# actionlink

Im trying to re-write this code to c# just for education purpose, i cant get it working tho :( what am i missing?

<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>


This is how far i've gotten:

@Html.ActionLink("Log off", "", "", new { onclick = "LogOutLink();" })


and the javascript:

<script>
function LogOutLink() {
document.getElementById('logoutForm').submit();
}
</script>


what am i missing? since i dont want the link to call any specific view or controller i have just left them blank as u can see, but it still wants to call for that function

Answer Source

You simply will need to rewrite it as:

@Html.ActionLink("Log off", "", "", new { }, new { onclick = "LogOutLink(); return false;" })

If you refer to this MSDN document, you will notice that the 4th argument is route values, and the 5th argument is the HTML attributes.



If you have jQuery loaded, you may also use jQuery to do it:

@Html.ActionLink("Log off", "", "", new { id = "LogOffId" });

In your javascript, add:

$(function(){
    $('#LogOffId').on('click', function(){
        $('#logoutForm').submit();
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download