2010-02-16 71 views
2

我有一个ActionLink的在我看来asp.net的MVC ActionLink的困难

<%= Html.ActionLink("action","controller") %> 

的操作有一个[AcceptVerbs(HttpVerbs.Post)] atttribute和lactionlink不起作用。

如何使它通过“POST”?

+2

你有POST通过

。 – mxmissile 2010-02-16 00:11:09

回答

4

要发布一个动作我用这个JavaScript函数:

function postToUrl(path, params, method) 
{ 
    method = method || "post"; // Set method to post by default, if not specified. 

    // The rest of this code assumes you are not using a library. 
    // It can be made less wordy if you use one. 
    var form = document.createElement("form"); 
    form.setAttribute("method", method); 
    form.setAttribute("action", path); 

    for (var key in params) { 
     var hiddenField = document.createElement("input"); 
     hiddenField.setAttribute("type", "hidden"); 
     hiddenField.setAttribute("name", key); 
     hiddenField.setAttribute("value", params[key]); 

     form.appendChild(hiddenField); 
    } 

    document.body.appendChild(form); // Not entirely sure if this is necessary 
    form.submit(); 
} 

它创建HTML表单,所以您不必在视图代码来创建它。这样你可以使用:

<button onclick="postToUrl('/Controller/Action');">Link</button> 
3

标签的ActionLink的只是创建了一个锚标记

<a href="url">link text</a> 

这本质上是一个GET动词。要做一个POST,你必须将actionlink包装在一个form标签中,并且你可以用一些jQuery来覆盖click功能。

<% using (Html.BeginForm("action","controller")) 
     { %> 
    <%= Html.ActionLink("Link Text", "action","controller") %> 
<% } %> 

<script> 
    $(document).ready(function() { 

     $("a").click(function() { 
      $(this).parents('form').submit(); 
      return false; 
     }); 

    }); 
</script> 
+1

+1,但是您可能希望使用'$(this).closest('form')'而不是'.parents'? – orip 2010-02-16 00:42:21

0

没有JS的另一种选择是使用提交按钮而不是链接。该按钮可以用CSS设置样式。

<%using (Html.BeginForm("action", "controller") {%> 
    <button type="submit">text</button> 
<%}%>