Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 1:24:22
ASP.NET表单实现多个按钮完成多个功能_[Asp.Net教程]

ASP.NET表单实现多个按钮完成多个功能_[Asp.Net教程]
在一个表单上需要多个按钮来完成不同的功能,比如一个简单的审批功能
image
如果是用webform那不需要讨论,但asp.net mvc中一个表单只能提交到一个Action处理,相对比较麻烦点。

方法一:使用客户端脚本

比如我们在View中这样写:

以下为引用的内容:

";’ />
";’ />
";’ />

在点击提交按钮时,先改变Form的action属性,使表单提交到按钮相应的action处理。

但有的时候,可能Action1和2的逻辑非常类似,也许只是将某个字段的值置为1或者0,那么分开到二个action中又显得有点多余了。

方法二:在Action中判断通过哪个按钮提交

在View中,我们不用任何客户端脚本处理,给每个提交按钮加好name属性:

以下为引用的内容:





然后在控制器中判断:

以下为引用的内容:

[HttpPost]
public ActionResult Index(string action /* 其它参数*/)
{
if (action=="审核通过")
{
//
}
else if (action=="审核不通过")
{
//
}
else
{
//
}
}

几年前写asp代码的时候经常用这样的方法…

View变得简单的,Controller复杂了。

太依赖说View,会存在一些问题。假若哪天客户说按钮上的文字改为“通过审核”,或者是做个多语言版的,那就麻烦了。

参考:http://www.ervinter.com/2009/09/25/asp-net-mvc-how-to-have-multiple-submit-button-in-form/

方法三:使用ActionSelector

关于ActionSelector的基本原理可以先看下这个POST使用ActionSelector控制Action的选择。

使用此方法,我们可以将控制器写成这样:

以下为引用的内容:

[HttpPost]
[MultiButton("action1")]
public ActionResult Action1()
{
//
return View();
}
[HttpPost]
[MultiButton("action2")]
public ActionResult Action2()
{
//
return View();
}

在 View中:

以下为引用的内容:





此时,Controller已经无须依赖于按钮的Value值。

MultiButtonAttribute的定义如下:

以下为引用的内容:

public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public MultiButtonAttribute(string name)
{
this.Name = name;
}
public override bool IsValidName(ControllerContext controllerContext,
string actionName, System.Reflection.MethodInfo methodInfo)
{
if (string.IsNullOrEmpty(this.Name))
{
return false;
}
return controllerContext.HttpContext.Request.Form.AllKeys.Contains(this.Name);
}
}


If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759