2012-12-11 72 views
0

的目的控制器上獲取按鈕ID:使用Ajax.BeginForm

我有一個Ajax.BeginForm後,我的目標是讓該按鈕ID控制器上。我見過使用Html.BeginForm的例子,但我需要一個Ajax形式,

驗證碼: C#MVC3

查看:

@using (Ajax.BeginForm("Save", "Valoration", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "HvmDetailTabStrip", OnSuccess = "OnSuccessSaveValoration" })) 
{ 
    <div id ="HvmDetailTabStrip"> 
     @(Html.Partial("_ValorationDetail")) 
    </div> 
    <button type="submit" style="display:none" id="db1"></button>  
    <button type="submit" style="display:none" id="db2"></button>  
}   

控制器:

[HttpPost] 
public ActionResult Save(ValorationModel model) 
{ 
    if ("db1")  
    { 
     var result = ValorationService.Save(ValorationModel); 
    } 
    else 
    { 
     // .... 
    }   

    return PartialView("_ValorationDetail", ValorationModel); 
} 
+0

我不確定這將甚至工作,因爲有2個'submit'按鈕是無效的代碼,並可能會被瀏覽器忽略。 –

+0

如果用戶點擊輸入/返回,他點擊了哪個按鈕? – BjarkeCK

+0

但是如果你沒有輸入,它允許用戶按下輸入/返回鍵提交表單,你可以在點擊按鈕時用一些javascript改變隱藏的輸入值。 – BjarkeCK

回答

2

你可以得到你的按鈕像這樣的值:

@using (Ajax.BeginForm("Save", "Valoration", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "HvmDetailTabStrip", OnSuccess = "OnSuccessSaveValoration" })) 
    { 
     <div id ="HvmDetailTabStrip"> 
       @(Html.Partial("_ValorationDetail")) 
     </div> 
     <button type="submit" name="submitButton" value="db1"></button>  
     <button type="submit" name="submitButton" value="db2"></button>  
    } 

而在你的控制器,你可以這樣寫:

[HttpPost] 
    public ActionResult Save(ValorationModel model) 
    { 
     string buttonValue = Request["submitButton"]; 

     if(buttonValue == "db1"){ 
     var result = ValorationService.Save(ValorationModel); 
     }else 
     { 
      .... 
     }   

     return PartialView("_ValorationDetail", ValorationModel); 
    } 

或者,如果你在方法傳遞的參數數量沒有關係,你可以使用這個:

[HttpPost] 
     public ActionResult Save(ValorationModel model, string submitButton) 
     { 
      if(submitButton == "db1"){ 
      var result = ValorationService.Save(ValorationModel); 
      }else 
      { 
       .... 
      }   

      return PartialView("_ValorationDetail", ValorationModel); 
     } 

其他方式你怎麼能解決你的問題是在這裏ASP.Net MVC - Submit buttons with same value

+0

非常感謝!很有用! :d – user1520494