【问题标题】:ActionLink with httpPost on same controller in asp.net MVC 5ActionLink 与 httpPost 在 asp.net MVC 5 中的同一控制器上
【发布时间】:2017-09-08 10:36:06
【问题描述】:

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

 @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 数据。

【问题讨论】:

  • 我认为你甚至不能用 actionlink 做到这一点;如果可以的话,它会在其中一个重载中
  • 你可以阅读这个主题:stackoverflow.com/questions/2048778/…
  • 问题是不清楚'Model'你可以直接在ActionLink中传入Model
  • 模型没有通过动作,这就是我通过它的原因
  • 你需要一个<form> 来发帖

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


【解决方案1】:

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>

【讨论】:

  • 这是唯一的办法兄弟。 MVC 必须遵循底层技术。默认情况下允许 Anchorlinks 发送帖子会违反规则。
  • Dheeraj 你能不能也提供你在 url
  • 你必须把你的方法的 url 放在 post 方法上。与您在表单帖子属性中编写的内容相同
  • Dheeraj 唯一的问题是我现在在控制器中获取数据为空
  • 你必须以这种格式传递数据:data: {attribute: "value"}。在服务器端,您应该将“属性”作为具有值的参数。
猜你喜欢
  • 1970-01-01
  • 2017-03-23
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 2015-01-04
  • 2018-07-07
相关资源
最近更新 更多