根据单击的提交按钮将表单发布到不同的MVC发布操作

时间:2014-01-14 15:13:57

标签: asp.net-mvc asp.net-mvc-4

我正在使用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))
        {

        }
   }

问题

  1. 有没有办法在不同的按钮点击时指向不同的POST动作方法(没有自定义路由)?
  2. 如果没有自定义路由,我们怎样才能使用自定义路由?
  3. 参考文献:

    1. Jimmy Bogard - Cleaning up POSTs in ASP.NET MVC

4 个答案:

答案 0 :(得分:79)

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

通过这种方式,您无需在服务器端执行任何特殊操作。

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

对于支持HMTL5的浏览器:只需定义您的提交按钮,如下所示:

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

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

$(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);
});

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

然后,您只需将data-form-action属性与所需的操作网址一起添加到按钮中,如下所示:

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

请注意,点击该按钮会更改表单的操作,之后,浏览器会将表单发布到所需的操作。

正如您所看到的,这不需要自定义路由,您可以使用标准的Url扩展方法,而且在现代浏览器中没有什么特别的功能。

答案 1 :(得分:20)

最佳答案1:

中提到的

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

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

    答案2

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

    第二种方法

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

    第三种方法:客户端脚本

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

答案 2 :(得分:5)

这听起来像你有一个带有2个输出的命令,我会选择在两个客户端和服务器上进行更改。

在客户端,使用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" ... />

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

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

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

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

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

或者您可以将ActionName属性用作别名

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

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

答案 3 :(得分:3)

你可以使用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
     }
});
相关问题