2010-03-11 87 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"); 
} 
相关问题