简体   繁体   English

在C#ActionLink中调用JavaScript函数

[英]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? 我试图将这段代码重写为C#只是出于教育目的,我无法通过tho :(我想念的是什么?

<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: 和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 因为我不希望链接调用任何特定的视图或控制器,所以我只是将它们留空,如您所见,但它仍然希望调用该函数

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. 如果您参考此MSDN文档 ,您会注意到第4个参数是路由值,第5个参数是HTML属性。



If you have jQuery loaded, you may also use jQuery to do it: 如果您已加载jQuery,则也可以使用jQuery来完成:

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

In your javascript, add: 在您的JavaScript中,添加:

$(function(){
    $('#LogOffId').on('click', function(){
        $('#logoutForm').submit();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM