2013-09-27 140 views
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) 
{   

} 
+0

您使用 – Rafay

+0

這jQuery的版本,我正在使用jQuery 1.5。 1 – enigma

回答

1

試試結合的Click事件處理程序,以保存和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); 
0

嘗試

ButtonClick Event " OnClick="MyButton_Click" " 
+0

感謝您的回覆。我提到問題,我不想使用點擊事件。 – enigma

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

+0

$(「#form」)。submit(function(event) {});我在Controller中得到了按鈕名稱,但驗證不起作用。 – enigma

相關問題