在asp.net MVC 5中的相同控制器上使用httpPost的ActionLink

时间:2017-09-08 10:36:06

标签: c# asp.net-mvc asp.net-mvc-5 .net-4.6

我有一个带有“忘记密码”链接的登录表单。 在登录提交时,我在“忘记密码”链接上调用了一些其他操作我正在调用一些不同的操作:

 @Html.ActionLink("Forgot Password", "ForgotPassword", "Login",  Model , new { @onclick = "return ValidateUsername();" })

我需要的是将其作为POST而不是GET发送。

我所拥有的是一个ASP.NET WebForm解决方案,我几乎完全转换为ASP.NET MVC。我正在使用LinkBut​​ton的一个地方。这是唯一的瓶颈。

修改

现在我正在使用以下JavaScript

$("a.anchor").click(function (e) {
    e.preventDefault(); // This will stop default behavior
    var validate = ValidateUsername();
    if (validate) {
        //alert(document.getElementById('usernameTextBox').value);

        var str = document.getElementById('usernameTextBox').value;
        $.ajax({
            type: "POST",
            url: "http://localhost/SSOMVC/Generic/ForgotPassword",
            data: "data",
            dataType: "text",
            success: function (resultData) {
                document.getElementById("usererror").textContent = resultData;
            },
            failure: function (error) {
            }
        });
    }
});

 @Html.ActionLink("Forgot Password", null, null, Model, new { @class = "anchor" })


  public class GenericController : Controller
    {


        [HttpPost]
        public ActionResult ForgotPassword(string data)
        {
           ....
            return Content(callResponse);
        }
    }

不知道为什么我总是在控制器中将数据设为null。

1 个答案:

答案 0 :(得分:2)

ActionLink在MVC中转换为锚标记。默认情况下,锚标记发送GET请求。

要发布Post请求,您可以在jquery中使用Ajax post调用。

   @Html.ActionLink("Forgot Password", "ForgotPassword", "Login",  Model , new { @onclick = "return ValidateUsername();" }, new { @class="anchor"})

    <script type="text/javascript">

    $("a.anchor").click(function(e){
      e.preventDefault(); // This will stop default behavior
     $.ajax({
      type: "POST",
      url: "<your classname/methodname>",
      data: <your data>,
      dataType: "text",
      success: function(resultData){
          alert("Call Complete");
      },
      failure: funciton(error){
}
});
    });    

</script>