我有一个具有相同值的多个提交按钮的单一表单。例如:“继续”。ASP.Net MVC - 提交具有相同值的按钮
现在,在ASP.Net MVC的后控制器方法中,我怎么知道哪个按钮被按下?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DepartmentDetails(string submitButton)
submitButton的值将始终为“继续”。我如何知道哪个按钮被按下。
我已为每个按钮提供了单独的ID。
谢谢。
我有一个具有相同值的多个提交按钮的单一表单。例如:“继续”。ASP.Net MVC - 提交具有相同值的按钮
现在,在ASP.Net MVC的后控制器方法中,我怎么知道哪个按钮被按下?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DepartmentDetails(string submitButton)
submitButton的值将始终为“继续”。我如何知道哪个按钮被按下。
我已为每个按钮提供了单独的ID。
谢谢。
试试这个:
<% using (Html.BeginForm())
{ %>
<input type="submit" value="Submit" name="Submit1Button" />
<input type="submit" value="Submit" name="Submit2Button" />
<%} %>
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection values)
{
string buttonName = values.AllKeys.Where((n) => n.EndsWith("Button")).SingleOrDefault();
return View();
}
}
谢谢。有用。 – 2009-12-29 05:39:33
,岂不更有意义,打破你的页面分为两个不同的形式?
然后,您可以使用Html.BeginForm HtmlHelper方法的参数为每个表单指定不同的Controller(s)Action方法。
我意识到这个问题是古老的,但只是碰到它,所以认为我会回答!
这就是我们使用:
/// <summary>
/// Attribute for Controller methods to decide whether a particular button
/// was clicked and hence whether the method can handle the action.
/// </summary>
public class IfButtonClickedAttribute : ActionMethodSelectorAttribute
{
private readonly IEnumerable<string> _buttonNames;
public IfButtonClickedAttribute(params string[] buttonNames)
{
_buttonNames = buttonNames;
}
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
if (controllerContext.HttpContext.Request.HttpMethod != "POST")
return false;
foreach (string buttonName in _buttonNames)
{
//this first test is for buttons or inputs that have the actual name specified
if (controllerContext.HttpContext.Request.Form[buttonName] != null)
return true;
}
return false;
}
}
然后你的行动你去:
[ActionName("SaveItem"), IfButtonClicked("SaveAsDraft")]
public ActionResult SaveAsDraft(){ ... }
[ActionName("SaveItem"), IfButtonClicked("SaveAsPublished")]
public ActionResult SaveAsPublished(){ ... }
你具有相同值的两个按钮,但你希望他们做不同的事情?这不会混淆用户吗?给按钮赋予不同的值有什么问题? – DOK 2009-12-28 17:23:58
'ID'无关紧要,'Name'是最重要的。那是不同的价值?这听起来像可能有一个简单的方法来寻找你想要的东西。提供更多的细节可能会有帮助。 – 2009-12-28 17:30:47
请发布您的HTML。 – 2009-12-28 17:39:01