101

谁能告诉我如何使用 ActionLink 和 POST 方法向 Controller 提交值?
我不想使用按钮。
我猜它与jquery有关。

4

17 回答 17

71

If you're using ASP MVC3 you could use an Ajax.ActionLink(), that allows you to specify a HTTP Method which you could set to "POST".

于 2011-05-31T07:45:57.527 回答
59

您不能使用 an ,ActionLink因为它只会呈现锚<a>标记。
您可以使用jQuery AJAX 帖子
或者只是使用或不使用 jQuery(这将是非 AJAX)调用表单的提交方法,也许在onclick您喜欢任何控制的情况下。

于 2010-01-12T13:23:55.857 回答
21

您可以使用 jQuery 为所有按钮执行 POST。只需给他们相同的 CssClass 名称。

使用“return false;” 如果您想在发布后执行服务器端 RedirectToAction,则在 onclick javascript 事件结束时,否则只需返回视图。

剃刀代码

@using (Html.BeginForm())
{
    @Html.HiddenFor(model => model.ID) 
    @Html.ActionLink("Save", "SaveAction", "MainController", null, new { @class = "saveButton", onclick = "return false;" })
}

jQuery 代码

$(document).ready(function () {
        $('.saveButton').click(function () {
            $(this).closest('form')[0].submit();
        });
    });

C#

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveAction(SaveViewModel model)
{
    // Save code here...

    return RedirectToAction("Index");
    //return View(model);
}
于 2012-01-23T23:51:26.450 回答
20

@Aidos 的正确答案只是想弄清楚,因为它隐藏在 @CodingWithSpike 对他的帖子的评论中。

@Ajax.ActionLink("Delete", "Delete", new { id = item.ApkModelId }, new AjaxOptions { HttpMethod = "POST" })
于 2012-12-11T03:25:03.920 回答
8

这是一个融入默认 ASP.NET MVC 5 项目的答案,我相信它可以在 UI 中很好地实现我的样式目标。使用纯 javascript 将表单提交到某些包含表单。

@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
   <a href="javascript:document.getElementById('logoutForm').submit()">
      <span>Sign out</span>
   </a>
}

完整显示的用例是 Web 应用程序导航栏中的注销下拉菜单。

@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
    @Html.AntiForgeryToken()

    <div class="dropdown">
        <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            <span class="ma-nav-text ma-account-name">@User.Identity.Name</span>
            <i class="material-icons md-36 text-inverse">person</i>
        </button>

        <ul class="dropdown-menu dropdown-menu-right ma-dropdown-tray">
            <li>
                <a href="javascript:document.getElementById('logoutForm').submit()">
                    <i class="material-icons">system_update_alt</i>
                    <span>Sign out</span>
                </a>
            </li>
        </ul>
    </div>
}
于 2017-08-02T02:01:53.320 回答
4

ActionLink 永远不会触发帖子。它总是触发 GET 请求。

于 2011-05-17T14:14:46.310 回答
2

使用以下调用操作链接:

<%= Html.ActionLink("Click Here" , "ActionName","ContorllerName" )%>

要提交表单值,请使用:

 <% using (Html.BeginForm("CustomerSearchResults", "Customer"))
   { %>
      <input type="text" id="Name" />
      <input type="submit" class="dASButton" value="Submit" />
   <% } %>

它将数据提交给客户控制器和 CustomerSearchResults 操作。

于 2011-03-10T11:01:26.373 回答
2

这取自 MVC 示例项目

@if (ViewBag.ShowRemoveButton)
      {
         using (Html.BeginForm("RemoveLogin", "Manage"))
           {
              @Html.AntiForgeryToken()
                  <div>
                     @Html.Hidden("company_name", account)
                     @Html.Hidden("returnUrl", Model.returnUrl)
                     <input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
                  </div>
            }
        }
于 2019-06-05T14:54:27.880 回答
1

Use this link inside Ajax.BeginForm

@Html.ActionLink(
    "Save", 
    "SaveAction", 
    null, 
    null, 
    onclick = "$(this).parents('form').attr('action', $(this).attr('href'));$(this).parents('form').submit();return false;" })

;)

于 2011-08-05T23:15:17.637 回答
1

我对这个问题的解决方案是一个相当简单的解决方案。我有一个页面,客户通过整个电子邮件进行搜索,另一个通过部分进行搜索,部分提取并显示一个列表,该列表有一个操作链接,该链接指向一个名为 GetByID 的操作结果并传入 id

GetByID 提取所选客户的数据,然后返回

return View("Index", model); 

这是post方法

于 2011-10-21T19:16:46.987 回答
1

我使用以下代码完成了同样的问题:

@using (Html.BeginForm("Delete", "Admin"))
{
       @Html.Hidden("ProductID", item.ProductID)
       <input type="submit" value="Delete" />
}
于 2014-11-20T07:09:59.410 回答
1

这对我来说一直是一个难以解决的问题。如何在 razor 和 html 中构建可以调用操作方法并将一个或多个值传递给特定操作方法的动态链接?我考虑了几个选项,包括自定义 html 助手。我只是想出了一个简单而优雅的解决方案。

风景

@model IEnumerable<MyMvcApp.Models.Product>

@using (Html.BeginForm()) {

     <table>
         <thead>
             <tr>
                 <td>Name</td>
                 <td>Price</td>
                 <td>Quantity</td>
            </tr>
        </thead>
        @foreach (Product p in Model.Products)
        {
            <tr>
                <td><a href="@Url.Action("Edit", "Product", p)">@p.Name</a></td>
                <td>@p.Price.ToString()</td>
                <td>@p.Quantity.ToString()</td>
            </tr>
         }
    </table>
}

动作方法

public ViewResult Edit(Product prod)
{
    ContextDB contextDB = new ContextDB();

    Product product = contextDB.Products.Single(p => p.ProductID == prod.ProductId);

    product = prod;

    contextDB.SaveChanges();

    return View("Edit");
}

这里的重点是 Url.Action 不关心操作方法是 GET 还是 POST。它将访问任一类型的方法。您可以使用将数据传递给操作方法

@Url.Action(string actionName, string controllerName, object routeValues)

routeValues 对象。我已经尝试过了,它有效。不,从技术上讲,您不是在发布帖子或提交表单,但如果 routeValues 对象包含您的数据,那么它是发布还是获取都没有关系。您可以使用特定的操作方法签名来选择正确的方法。

于 2011-12-19T16:45:01.617 回答
1

这是我解决问题的方法。这是具有 2 种操作方法的控制器

public class FeedbackController : Controller
{
public ActionResult Index()
{
   var feedbacks =dataFromSomeSource.getData;
   return View(feedbacks);
}

[System.Web.Mvc.HttpDelete]
[System.Web.Mvc.Authorize(Roles = "admin")]
public ActionResult Delete([FromBody]int id)
{
   return RedirectToAction("Index");
}
}

在视图中,我渲染了以下结构。

<html>
..
<script src="~/Scripts/bootbox.min.js"></script>
<script>
function confirmDelete(id) {
  bootbox.confirm('@Resources.Resource.AreYouSure', function(result) {
    if (result) {
      document.getElementById('idField').value = id;
      document.getElementById('myForm').submit();
    }
  }.bind(this));
}
</script>

@using (Html.BeginForm("Delete", "Feedback", FormMethod.Post, new { id = "myForm" }))
{
  @Html.HttpMethodOverride(HttpVerbs.Delete)
  @Html.Hidden("id",null,new{id="idField"})
  foreach (var feedback in @Model)
  {
   if (User.Identity.IsAuthenticated && User.IsInRole("admin"))
   {
    @Html.ActionLink("Delete Item", "", new { id = @feedback.Id }, new { onClick = "confirmDelete("+feedback.Id+");return false;" })
   }
  }
...
</html>

Razor View 的兴趣点

  1. confirmDelete(id)单击生成的链接时调用的JavaScript 函数@Html.ActionLink

  2. confirmDelete()功能需要被点击项目的ID。此项目是从onClick处理程序传递的confirmDelete("+feedback.Id+");return false;注意处理程序返回 false 以防止默认操作 - 即获取对目标的请求。OnClick按钮的事件可以附加到列表中所有按钮的 jQuery 作为替代(可能会更好,因为它会在 HTML 页面中减少文本,并且可以通过data-属性传递数据)。

  3. 表格有id=myForm,才能找到它confirmDelete()

  4. 形式包括@Html.HttpMethodOverride(HttpVerbs.Delete)为了使用HttpDelete动词,作为标有 的动作HttpDeleteAttribute

  5. 在 JS 函数中,我确实使用了动作确认(在外部插件的帮助下,但标准确认也可以正常工作。不要忘记bind()在回调或var that=this(无论您喜欢什么)中使用。

  6. 表单有一个带有id='idField'和的隐藏元素name='id'。所以在确认result==true

请求网址http://localhost:38874/Feedback/Delete

请求方法:POST 状态码:302 找到

响应标头

Location:/Feedback Host:localhost:38874 Form Data X-HTTP-Method-Override:DELETE id:5

如您所见,它是带有 X-HTTP-Method-Override:DELETE 的 POST 请求,并且正文中的数据设置为“id:5”。响应具有重定向到索引操作的 302 代码,这样您在删除后刷新屏幕。

于 2015-07-30T20:15:00.140 回答
0

jQuery.post()如果您有自定义数据,它将起作用。如果要发布现有表单,使用ajaxSubmit().

而且您不必自行设置此代码ActionLink,因为您可以在事件中附加链接处理程序document.ready()(无论如何这是首选方法),例如使用$(function(){ ... })jQuery 技巧。

于 2010-01-12T12:37:10.020 回答
0

我建议您保持纯粹的 REST 原则并使用 HTTP 删除进行删除。不幸的是,HTML Specs 只有 HTTP Get & Post。一个标签只能是一个 HTTP Get。表单标签可以执行 HTTP Get 或 Post。幸运的是,如果您使用 ajax,您可以执行 HTTP 删除,这是我推荐的。有关详细信息,请参阅以下帖子:Http Deletes

于 2011-07-31T05:34:02.443 回答
0

遇到需要从搜索(索引)页面发布到结果页面的问题。我不需要@Vitaliy 所说的那么多,但它为我指明了正确的方向。我所要做的就是:

@using (Html.BeginForm("Result", "Search", FormMethod.Post)) {
  <div class="row">
    <div class="col-md-4">
      <div class="field">Search Term:</div>
      <input id="k" name="k" type="text" placeholder="Search" />
    </div>
  </div>
  <br />
  <div class="row">
    <div class="col-md-12">
      <button type="submit" class="btn btn-default">Search</button>
    </div>
  </div>
}

我的控制器具有以下签名方法:

[HttpPost]
public async Task<ActionResult> Result(string k)
于 2017-02-08T15:18:57.540 回答
0

调用 $.post() 将不起作用,因为它是基于 Ajax 的。因此,为此需要使用混合方法。

以下是对我有用的解决方案。

步骤: 1. 为 href 创建 URL,它使用 url 和参数调用 a 方法 2. 使用 JavaScript 方法调用普通 POST

解决方案:

在 .cshtml 中:

<a href="javascript:(function(){$.postGo( '@Url.Action("View")', { 'id': @receipt.ReceiptId  } );})()">View</a>

注意:匿名方法应该包含在 (....)() 中,即

(function() {
    //code...
})();

postGo在 JavaScript 中定义如下。休息很简单。。

@Url.Action("View")为调用创建 url

{ 'id': @receipt.ReceiptId }创建参数作为对象,然后在 postGo 方法中将其转换为 POST 字段。这可以是您需要的任何参数

在 JavaScript 中:

(function ($) {
    $.extend({
        getGo: function (url, params) {
            document.location = url + '?' + $.param(params);
        },
        postGo: function (url, params) {
            var $form = $("<form>")
                .attr("method", "post")
                .attr("action", url);
            $.each(params, function (name, value) {
                $("<input type='hidden'>")
                    .attr("name", name)
                    .attr("value", value)
                    .appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);

我用于 postGo 的参考 URL

使用 jQuery(插件?)的非 ajax GET/POST

http://nuonical.com/jquery-postgo-plugin/

于 2015-07-29T10:54:12.247 回答