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

我需要做些什么才能获得单击的提交按钮的实际值可能是什么问题或解决方法?

4

4 回答 4

7

显示此页面。

ASP.NET MVC – 同一个表单中的多个按钮 - David Findley 的博客

创建 ActionMethodSelectorAttribute 继承类。

于 2010-03-11T15:22:31.130 回答
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
    }
}
于 2010-03-11T07:14:54.347 回答
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");
}
于 2013-05-17T19:35:28.530 回答
-2

解决方法:使用 javascript 提交表单而不是提交按钮

于 2010-03-11T06:51:07.250 回答