asp.net-mvc 根据单击的提交按钮将表单发布到不同的 MVC 发布操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21116999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:26:35  来源:igfitidea点击:

Posting form to different MVC post action depending on the clicked submit button

asp.net-mvcasp.net-mvc-4

提问by LCJ

I am using ASP.Net MVC 4. I have multiple buttons on a view.. At present I am calling the same action method; and I am distinguishing the clicked button using a nameattribute.

我正在使用ASP.Net MVC 4. 我在一个视图上有多个按钮。目前我正在调用相同的操作方法;我正在使用name属性区分单击的按钮。

@using (Html.BeginForm("Submit", "SearchDisplay", new { id = Model == null ? Guid.NewGuid().ToString() : Model.SavedSearch }, FormMethod.Post))
{
    <div class="leftSideDiv">
        <input type="submit" id="btnExport" class="exporttoexcelButton" 
        name="Command" value="Export to Excel" />
    </div>

    <div class="pageWrapperForSearchSubmit">
        <input type="submit" class="submitButton" 
         value="Submit" id="btnSubmitChange" />
    </div>
}

//ACTION

//行动

    [HttpPost]
    public ActionResult Submit(SearchCostPage searchModel, string Command)
    {
        SessionHelper.ProjectCase = searchModel.ProjectCaseNumber;

        if (string.Equals(Command, Constants.SearchPage.ExportToExcel))
        {

        }
   }

QUESTIONS

问题

  1. Is there a way to direct to different POST action methods on different button clicks (without custom routing)?
  2. If there is no way without custom routing, how can we do it with custom routing?
  1. 有没有办法在不同的按钮点击(没有自定义路由)上指向不同的 POST 操作方法?
  2. 如果没有自定义路由就没有办法,那么自定义路由怎么办呢?

References:

参考:

  1. Jimmy Bogard - Cleaning up POSTs in ASP.NET MVC
  1. Jimmy Bogard - 清理 ASP.NET MVC 中的 POST

采纳答案by LCJ

BEST ANSWER 1:

最佳答案 1:

ActionNameSelectorAttributementioned in

ActionNameSelectorAttribute中提到

  1. How do you handle multiple submit buttons in ASP.NET MVC Framework?

  2. ASP.Net MVC 4 Form with 2 submit buttons/actions

  1. 你如何处理 ASP.NET MVC 框架中的多个提交按钮?

  2. 带有 2 个提交按钮/操作的 ASP.Net MVC 4 表单

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

ANSWER 2

答案 2

Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor

参考:dotnet-tricks - 在同一个表单上处理多个提交按钮 - MVC Razor

Second Approach

第二种方法

Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

添加用于处理取消按钮单击的新表单。现在,点击取消按钮,我们将发布第二个表单并将重定向到主页。

Third Approach: Client Script

第三种方法:客户端脚本

<button name="ClientCancel" type="button" 
    onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" 
style="display:none;"></a>

回答by JotaBe

You can choose the url where the form must be posted (and thus, the invoked action) in different ways, depending on the browser support:

您可以选择以不同方式发布表单的 url(以及调用的操作),具体取决于浏览器支持:

In this way you don't need to do anything special on the server side.

这样你就不需要在服务器端做任何特别的事情。

Of course, you can use Urlextensions methods in your Razor to specify the form action.

当然,您可以Url在 Razor 中使用扩展方法来指定表单操作。

For browsers supporting HMTL5:simply define your submit buttons like this:

对于支持 HMTL5 的浏览器:只需像这样定义提交按钮:

<input type='submit' value='...' formaction='@Url.Action(...)' />

For older browsersI recommend using an unobtrusive script like this (include it in your "master layout"):

对于较旧的浏览器,我建议使用像这样的不显眼的脚本(将其包含在“主布局”中):

$(document).on('click', '[type="submit"][data-form-action]', function (event) {
  var $this = $(this);
  var formAction = $this.attr('data-form-action');
  $this.closest('form').attr('action', formAction);
});

NOTE: This script will handle the click for any element in the page that has type=submitand data-form-actionattributes. When this happens, it takes the value of data-form-actionattribute and set the containing form's action to the value of this attribute. As it's a delegated event, it will work even for HTML loaded using AJAX, without taking extra steps.

注意:此脚本将处理页面中具有type=submitdata-form-action属性的任何元素的点击。发生这种情况时,它会获取data-form-action属性的值并将包含表单的操作设置为该属性的值。因为它是一个委托事件,它甚至可以用于使用 AJAX 加载的 HTML,而无需采取额外的步骤。

Then you simply have to add a data-form-actionattribute with the desired action URL to your button, like this:

然后,您只需data-form-action将具有所需操作 URL的属性添加到您的按钮,如下所示:

<input type='submit' data-form-action='@Url.Action(...)' value='...'/>

Note that clicking the button changes the form's action, and, right after that, the browser posts the form to the desired action.

请注意,单击该按钮会更改表单的操作,然后浏览器立即将表单发送到所需的操作。

As you can see, this requires no custom routing, you can use the standard Urlextension methods, and you have nothing special to do in modern browsers.

如您所见,这不需要自定义路由,您可以使用标准Url扩展方法,并且在现代浏览器中您没有什么特别的事情要做。

回答by James

This sounds to me like what you have is one command with 2 outputs, I would opt for making the change in bothclient and server for this.

这听起来像你对我有什么是2个输出一个命令,我会选择做的改变客户端和服务器这一点。

At the client, use JS to build up the URL you want to post to (use JQuery for simplicity) i.e.

在客户端,使用 JS 构建您要发布到的 URL(为简单起见,使用 JQuery)即

<script type="text/javascript">
    $(function() {
        // this code detects a button click and sets an `option` attribute
        // in the form to be the `name` attribute of whichever button was clicked
        $('form input[type=submit]').click(function() {
            var $form = $('form');
            form.removeAttr('option');
            form.attr('option', $(this).attr('name'));
        });
        // this code updates the URL before the form is submitted
        $("form").submit(function(e) { 
            var option = $(this).attr("option");
            if (option) {
                e.preventDefault();
                var currentUrl = $(this).attr("action");
                $(this).attr('action', currentUrl + "/" + option).submit();     
            }
        });
    });
</script>
...
<input type="submit" ... />
<input type="submit" name="excel" ... />

Now at the server side we can add a new route to handle the excel request

现在在服务器端我们可以添加一个新的路由来处理 excel 请求

routes.MapRoute(
    name: "ExcelExport",
    url: "SearchDisplay/Submit/excel",
    defaults: new
    {
        controller = "SearchDisplay",
        action = "SubmitExcel",
    });

You can setup 2 distinct actions

您可以设置 2 个不同的操作

public ActionResult SubmitExcel(SearchCostPage model)
{
   ...
}

public ActionResult Submit(SearchCostPage model)
{
   ...
}

Or you can use the ActionNameattribute as an alias

或者您可以使用该ActionName属性作为别名

public ActionResult Submit(SearchCostPage model)
{
   ...
}

[ActionName("SubmitExcel")]
public ActionResult Submit(SearchCostPage model)
{
   ...
}

回答by Matt Bodily

you can use ajax calls to call different methods without a postback

您可以使用 ajax 调用来调用不同的方法而无需回发

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});