2010-03-11 85 views
5

我在asp.net mvc(C#)應用程序中有兩個提交按鈕的窗體。當我單擊Google Chrome中的任何提交按鈕時,默認情況下,提交按鈕的值是第一個提交按鈕的值。在單個窗體中使用兩個提交按鈕

下面是HTML:

<input type="submit" value="Send" name="SendEmail" /> 
<input type="submit" value="Save As Draft" name="SendEmail" /> 
<input type="button" value="Cancel" /> 

當我點擊Save As Draft按鈕,在控制器的作用下,它被「發送」爲SendEmail值。

這裏是動作:

public ActionResult SendEmail(string SendEmail, FormCollection form) 
{ 
     if(SendEmail == "Send") 
     { 
      //Send Email 
     } 
     else 
     { 
      //Save as draft 
     } 
     return RedirectToAction("SendEmailSuccess"); 
} 

當我得到的FormCollection的價值,它顯示了 「發送」。即form["SendEmail"]給出Send

什麼可能是問題或解決辦法我需要做的,以獲得點擊提交按鈕的實際價值?

+0

您的代碼看起來不錯,該技術應該工作。可能會嘗試檢查HTTP POST以查看究竟是什麼被髮送回服務器。 – DavGarcia 2010-03-11 06:51:50

+0

它只發生在谷歌瀏覽器中,但在IE和Firefox中,它運行良好。 – Prasad 2010-03-11 06:56:17

+0

Chrome是什麼? – Ted 2013-12-04 00:51:30

回答

-2

解決方法:使用JavaScript submiting的形式,而不是提交按鈕

5

試試這個:

<input type="submit" value="Send" name="send" /> 
<input type="submit" value="Save As Draft" name="save" /> 

和:

public ActionResult SendEmail(string send, FormCollection form) 
{ 
    if (!string.IsNullOrEmpty(send)) 
    { 
     // the Send button has been clicked 
    } 
    else 
    { 
     // the Save As Draft button has been clicked 
    } 
} 
+0

單擊Google Chrome中的任一按鈕時,它將返回值「發送」,但在IE中,單擊「另存爲草稿」時返回空值。這個問題只在使用google chrome – Prasad 2010-03-11 07:31:35

+0

您是否正在仔細閱讀我的文章?你有沒有注意到按鈕的名稱和傳遞給動作的參數的名稱? – 2010-03-11 08:22:09

+0

是的,我根據你的答案改變了我的代碼,但問題是一樣的。我不知道谷歌瀏覽器有什麼奇怪的。 – Prasad 2010-03-11 10:21:09

1

隱藏的Html元素將與您的表單一起提交,因此您可以在提交之前添加隱藏的元素並在按鈕上點擊進行修改。返回true以繼續表單提交。

@Html.Hidden("sendemail", true) 
<input type="submit" value="Send" 
     onclick="$('#sendemail').val(true); return true" /> 
<input type="submit" value="Save As Draft" 
     onclick="$('#sendemail').val(false); return true;" /> 

現在,您可以將值從表單集合中提取出來。

public ActionResult SendEmail(FormCollection form) 
{ 
    if(Boolean.Parse(form["sendemail"])) 
    { 
     //Send Email 
    } 
    else 
    { 
     //Save as draft 
    } 
    return RedirectToAction("SendEmailSuccess"); 
} 

不是使用的FormCollection直接雖然相反,最好的做法是創建一個包含指定屬性的視圖模型。

視圖模型

public class FooViewModel 
{ 
    public bool SendEmail { get; set; } 
    // other stuff 
} 

HTML

// MVC sets a hidden input element's id attribute to the property name, 
// so it's easily selectable with javascript 
@Html.HiddenFor(m => m.SendEmail) 

// a boolean HTML input can be modified by setting its value to 
// 'true' or 'false' 
<input type="submit" value="Send" 
     onclick="$('#SendEmail').val(true); return true" /> 
<input type="submit" value="Save As Draft" 
     onclick="$('#SendEmail').val(false); return true;" /> 

控制器動作

public ActionResult SendEmail(FooViewModel model) 
{ 
    if(model.SendEmail) 
    { 
     //Send Email 
    } 
    else 
    { 
     //Save as draft 
    } 
    return RedirectToAction("SendEmailSuccess"); 
} 
相關問題