2017-06-19 47 views
0

我正在處理小型MVC應用程序,並在我的視圖中,有012個按鈕,它們都調用了相同的Action,這裏是定義按鈕:三個按鈕正在調用同一個控制器的Action方法 - 確定哪一個調用的方法

<button type="submit" class="btn btn-success pull-right" id="btnSave" value="tabOne"><i class="fa fa-save"></i> Submit changes </button> 

而且還有他們三個這樣的,我怎麼能知道哪一個調用的方法,因爲它們位於三個分離選項卡和上提交(保存更改)每個標籤需要重定向到不同的看法,所以這就是爲什麼我需要認識到了哪個按鈕調用我的[HttpPost] Edit操作方法..

這是怎麼看起來方法,我調用:

[HttpPost] 
public ActionResult Edit(ArticleEditViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
//Rest of some code 
//Here I need to determine which button called this method so I can redirect user //to a corresponding view, for example 
    if(button1 invoked me) 
    { 
     return RedirectToAction("Edit", "Article"); 
    } 
    else if(button 2 invoked me) 
    { 
     return RedirectToAction("Index", "Article"); 
    } 
} 

所以,球員這幾乎是所有的,我有標籤控件,3個按鈕,這是submiting相同的動作方法,我需要找出哪一個調用一個方法。

謝謝你們 乾杯

回答

1

給一個name屬性按鈕具有不同值的

<button type="submit" name="clickedFrom" id="btnSave" value="tabOne" >Tab one</button> 
<button type="submit" name="clickedFrom" id="btnSave2" value="tabTwo" >Tab Two</button> 

和添加一個參數到你的http後動作方法

[HttpPost] 
public ActionResult Edit(ArticleEditViewModel model,string clickedFrom) 
{ 
    // to do : Check value of clickedFrom and do something 
    // to do : return something 
} 

當表單被提交時,瀏覽器會在請求主體中的clickedFrom鍵上發送點擊按鈕的值

+0

我應該做這個字符串clickedFrom可爲空參數,萬一哪天我需要從一些其他視圖調用它,我不會通過任何東西進入我的編輯操作方法,或者這是確定要離開這樣說,這只是我可能會檢查(clickedFrom!= null){//做些什麼}? –

+0

'string'已經是可以爲空的類型。 – Shyju

+0

和有類型的都沒有,所以如果你調用爲例編輯方法,你不提供clickedFrom的價值,情況可能是危險的? :d –

0

在你的事件處理程序,你傳遞一個event作爲參數來獲得與所發生的事情的具體信息。您正在尋找的具體房產是Event.target

// Taken from Event.target MDN, this will hide the caller of the event 
$("#btnSave").click(function(event) { 
    event.target.style.visibility = 'hidden'; 
}); 

我用jQuery來爲簡潔綁定事件,它與香草JS之間的差異是在此實例中疏忽

0

除非通過javascript傳遞參數,否則我認爲這是不可能的。

你爲什麼不只是傳遞價值屬性「塔博恩」,「tabTwo」或「tabThree」?

相關問題