Asp.net mvc 4 在同一视图上提交多个按钮
我需要在同一个视图上有多个按钮,但由于某些原因它不能工作。我已经看了同样的问题,但我还没有找到解决办法 如何知道在视图中执行哪个按钮 视图:Asp.net mvc 4 在同一视图上提交多个按钮,asp.net-mvc-4,visual-studio-2012,Asp.net Mvc 4,Visual Studio 2012,我需要在同一个视图上有多个按钮,但由于某些原因它不能工作。我已经看了同样的问题,但我还没有找到解决办法 如何知道在视图中执行哪个按钮 视图: 您应该在一个表单中使用一个提交按钮 不同的控制器方法的不同形式这是最好的方法,这是我以前为类似向导的视图所做的事情,这是可能的,但我认为您的方法行不通 相反,我建议尝试我使用的基于 您也可以不使用表单元素进行提交,也可以使用jQuery/Javascript提交表单 这个问题有很多解决方案: 选项1- 类似于此(我不检查代码是否正确,请耐心等待): @使用
您应该在一个表单中使用一个提交按钮
不同的控制器方法的不同形式这是最好的方法,这是我以前为类似向导的视图所做的事情,这是可能的,但我认为您的方法行不通 相反,我建议尝试我使用的基于
您也可以不使用表单元素进行提交,也可以使用jQuery/Javascript提交表单 这个问题有很多解决方案: 选项1- 类似于此(我不检查代码是否正确,请耐心等待):
@使用(Html.BeginForm(“Controller”,“Action1”,FormMethod.Post,new{id=“MyForm1”}))
{
Bt1
}
@使用(Html.BeginForm(“Controller”,“Action2”,FormMethod.Post,new{id=“MyForm2”}))
{
Bt2
}
现在,您指向两个不同的操作,您可以清楚地对它们进行编程,并且仍然可以使用视图(“SameViewForBothForms”)
或重定向到“MainView”返回它们
选项2-只有一个表单,有两个按钮>不是提交类型,而是简单的按钮,您可以使用Javascript函数更改隐藏字段“buttonName”的值(在JS函数中更改此值)
选项3-
多种或单一形式的任何混合都是可能的……尝试以下解决方案:
public ActionResult NewPublication(string btnSearch)
{
if (!string.IsNullOrEmpty(btnSearch))
{
//btnSearch was clicked
}
else
{
//btnSave was clicked
}
}
检查一下这个
希望有帮助。您可以从下面的名称标签中识别您的按钮,您需要在控制器中这样检查
if (Request.Form["btnSearch"] != null)
{
//Write your code here
}
else if (Request.Form["btnSave"] != null)
{
//Write your code here
}
此问题的可能重复项已超过4天,您确定当前的任何答案都不是“正确答案”吗?如果是,则选择它作为正确答案,如果不是,则请向我们提供有关您的问题的更多详细信息。谢谢
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Publication", action = "Index", id = UrlParameter.Optional }
);
}
@using (Html.BeginForm("Controller", "Action1", FormMethod.Post, new { id="MyForm1"}))
{
<button type="submit" id="btn1">Bt1</button>
}
@using (Html.BeginForm("Controller", "Action2", FormMethod.Post, new { id="MyForm2"}))
{
<button type="submit" id="btn2">Bt2</button>
}
public ActionResult NewPublication(string btnSearch)
{
if (!string.IsNullOrEmpty(btnSearch))
{
//btnSearch was clicked
}
else
{
//btnSave was clicked
}
}
if (Request.Form["btnSearch"] != null)
{
//Write your code here
}
else if (Request.Form["btnSave"] != null)
{
//Write your code here
}