【问题标题】:how can I check which submit button was pressed?如何检查按下了哪个提交按钮?
【发布时间】:2013-10-03 06:40:38
【问题描述】:

我为表单提交设置了两个提交按钮。 我想知道单击了哪个提交按钮,而没有对每个按钮应用 .click() 事件。 我正在使用 ASP.NET MVC 3 并希望在 Controller 中获取单击的按钮名称。

设置如下:

<a class="anchorbutton">
  <input  type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input  type="submit" value="Save & Next" id="SaveNext" class="hrbutton  anchorbutton"/>           


 $('#form').live('submit', function (e)    
{      
    e.preventDefault();
    var form = $('#form');      
    $.ajax({
        cache: false,
        async: true,
        type: "POST",
        url: form.attr('action'),
        data: form.serialize(),
        success: function (data) {
            $.ajax({
                url: 'url',
                dataType: "html",
                success: function (data) {
                    $("#div").html(data);                     

                }
            });
        }
    });
    return false;
});


[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{         

}

【问题讨论】:

  • 你使用的是哪个 jquery 版本
  • 我使用的是 Jquery 1.5.1

标签: asp.net-mvc jquery


【解决方案1】:

试试

    ButtonClick Event " OnClick="MyButton_Click" "

【讨论】:

  • 感谢您的回复。我有问题提到我不想使用点击事件。
【解决方案2】:

给你的按钮命名:

<a class="anchorbutton">
    <button type="submit" name="save" id="Save" class="hrbutton">Save</button>
</a>
<button type="submit" name="savenext" id="SaveNext" class="hrbutton anchorbutton">Save & Next</button>

然后您的控制器操作可以获取具有相同名称的参数并检查它是否具有值:

[HttpPost]
public ActionResult Post(string save, string saveNext, FormCollection form)
{
    if (!string.IsNullOrEmpty(save))
    {
        // The Save button was clicked
    }
    else if (!string.IsNullOrEmpty(saveNext))
    {
        // The Save & Next button was clicked
    }
    else
    {
        // None of the submit buttons were used or clicked to submit the form.
        // The user simply pressed the Enter key while the focus was inside
        // some of the input fields of the form
    }

    ...
}

哦,顺便说一句,.live jQuery 函数已被弃用。请改用.on。

【讨论】:

  • $("#form").submit(function (event) {});我在 Controller 中获得了按钮名称,但验证不起作用。
【解决方案3】:

尝试将 click 事件处理程序绑定到 Save 和 SaveAndNext 按钮,如

$(document).delegate("#Save,#SaveAndNext","click",function(e){
 console.log($(this).attr("id"));//here you will know which button was pressed
 //next you can check if the form is valid or not
 if($(this).closest('form').valid()){
 //form is valid submit it ajax(ily)

 }else{
 //form is not valid
 }
});

你也可以缓存选择器

var $this = $(this);

【讨论】:

    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    相关资源
    最近更新 更多