我为表单提交设置了两个提交按钮。 我想知道单击了哪个提交按钮而没有对每个提交.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)
{
}
答案 0 :(得分: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
。
答案 1 :(得分:1)
尝试将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);
答案 2 :(得分:0)
尝试
ButtonClick Event " OnClick="MyButton_Click" "