ActionLink with httpPost on same controller in asp.net MVC 5

1.4k Views Asked by At

I have a login form with "forgot password" link. On login submit I am calling some other action while on "forgot password" link I am calling some different action:

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

What I need is to send it as POST instead of GET.

What I have was a ASP.NET WebForm solution which I have almost completely converted into ASP.NET MVC. One place I was using LinkButton. That is the only bottle neck remains.


Edit:

Now I am using following 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);
        }
    }

Don't know why I am always getting data as null in the controller.

1

There are 1 best solutions below

5
On BEST ANSWER

ActionLink is converted into anchor tag in MVC. An anchor tag by default sends a GET Request.

To make a Post request, you can use Ajax post call in jquery.

   @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>