【问题标题】:Can I forward to a HttpPost method without a BeginForm?我可以转发到没有 BeginForm 的 HttpPost 方法吗?
【发布时间】:2014-07-17 14:55:18
【问题描述】:

我是 MVC 新手,但还没有找到方法。

在视图中我有这个克隆按钮:

<a href="@Url.Action("Clone", "Game", new { pModelId = Model.Id })" class="btn btn-default btn-xs">
                            <i class="fa fa-plus"></i>Clone Game</a>

在我的控制器中:

[HttpPost]
    public ActionResult Clone(int pGameId)
    {
        int lClonedGameId = mGameRepository.CloneGame(pGameId);
        return RedirectToAction("Show", new { id = lClonedGameId, message = "Your game was cloned succesfully" });
    }

由于 [HttpPost],我得到了 404,但我不想让它成为 [HttpGet],因为它会写入数据库。有没有办法让那个按钮在没有 BeginForm 或类似的东西的情况下转到 HttpPost 方法?

【问题讨论】:

  • 链接总是意味着 GET 请求。如果您希望浏览器发出 POST 请求,则需要一个表单。您使用 MVC 的事实没有任何区别。

标签: asp.net-mvc http-post


【解决方案1】:

如果这只是使用链接而不是按钮提交表单的问题,我建议您添加表单并在按下链接时使用 javascript 提交表单(以下代码假设您使用的是 jQuery):

@using (Html.BeginForm("Clone", "Game", FormMethod.Post, new {id = "form1"}))
{
    //Your other elements go here
    <a href="#" class="cloneGameSubmit">CloneGame</a>
}

并挂钩脚本:

$(function() {
    $("a.cloneGameSubmit").click(function () {
        $("#form1").submit();
    });
});

【讨论】:

  • 请注意,您需要一个具有name 属性的隐藏字段pGameId 才能绑定到操作方法参数。
  • 我试过了,但仍然需要弄清楚那个隐藏字段=P,我需要阅读很多关于网络的内容。--------刚刚找到了方法。谢谢,您的回答正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 2021-09-28
  • 2012-04-19
  • 1970-01-01
相关资源
最近更新 更多