1

我为表单提交设置了两个提交按钮。我想知道单击了哪个提交按钮,而没有对每个按钮应用 .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)
{         

}
4

3 回答 3

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
    }

    ...
}

哦,顺便说一句,.livejQuery 函数已被弃用。改为使用.on

于 2013-09-27T04:33:32.230 回答
2

尝试将 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);
于 2013-09-28T19:52:44.890 回答
0

尝试

    ButtonClick Event " OnClick="MyButton_Click" "
于 2013-09-27T04:32:00.250 回答