MVC中实现多按钮提交(转)
有时候会遇到这种情况:在一个表单上需要多个按钮来完成不同的功能,比如一个简单的审批功能。
如果是用webform那不需要讨论,但asp.net mvc中一个表单只能提交到一个Action处理,相对比较麻烦点。
方法一:使用客户端脚本
比如我们在View中这样写:
- <input type="submit" value="审核通过" onclick='this.form.action="<%=Url.Action("Action1") %>";' />
- <input type="submit" value="审核不通过" onclick='this.form.action="<%=Url.Action("Action2") %>";' />
- <input type="submit" value="返回" onclick='this.form.action="<%=Url.Action("Action3") %>";' />
<input type="submit" value="审核通过" onclick='this.form.action="<%=Url.Action("Action1") %>";' />
<input type="submit" value="审核不通过" onclick='this.form.action="<%=Url.Action("Action2") %>";' />
<input type="submit" value="返回" onclick='this.form.action="<%=Url.Action("Action3") %>";' />
在点击提交按钮时,先改变Form的action属性,使表单提交到按钮相应的action处理。
但有的时候,可能Action1和2的逻辑非常类似,也许只是将某个字段的值置为1或者0,那么分开到二个action中又显得有点多余了。
方法二:在Action中判断通过哪个按钮提交
在View中,我们不用任何客户端脚本处理,给每个提交按钮加好name属性:
- <input type="submit" value="审核通过" name="action" />
- <input type="submit" value="审核不通过" name="action"/>
- <input type="submit" value="返回" name="action"/>
<input type="submit" value="审核通过" name="action" />
<input type="submit" value="审核不通过" name="action"/>
<input type="submit" value="返回" name="action"/>
然后在控制器中判断:
- [HttpPost]
- public ActionResult Index(string action /* 其它参数*/)
- {
- if (action=="审核通过")
- {
- //
- }
- else if (action=="审核不通过")
- {
- //
- }
- else
- {
- //
- }
- }
[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();
- }
[HttpPost]
[MultiButton("action1")]
public ActionResult Action1()
{
//
return View();
}
[HttpPost]
[MultiButton("action2")]
public ActionResult Action2()
{
//
return View();
}
在 View中:
- <input type="submit" value="审核通过" name="action1" />
- <input type="submit" value="审核不通过" name="action2"/>
- <input type="submit" value="返回" name="action3"/>
<input type="submit" value="审核通过" name="action1" />
<input type="submit" value="审核不通过" name="action2"/>
<input type="submit" value="返回" name="action3"/>
此时,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);
- }
- }
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);
}
}
方法四、改进
Thomas Eyde就方法三的方案给出了个改进版:
Controller:
- [HttpPost]
- [MultiButton(Name = "delete", Argument = "id")]
- public ActionResult Delete(string id)
- {
- var response = System.Web.HttpContext.Current.Response;
- response.Write("Delete action was invoked with " + id);
- return View();
- }
[HttpPost]
[MultiButton(Name = "delete", Argument = "id")]
public ActionResult Delete(string id)
{
var response = System.Web.HttpContext.Current.Response;
response.Write("Delete action was invoked with " + id);
return View();
}
- <input type="submit" value="not important" name="delete" />
- <input type="submit" value="not important" name="delete:id" />
<input type="submit" value="not important" name="delete" />
<input type="submit" value="not important" name="delete:id" />
MultiButtonAttribute定义:
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
- public class MultiButtonAttribute : ActionNameSelectorAttribute
- {
- public string Name { get; set; }
- public string Argument { get; set; }
- public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
- {
- var key = ButtonKeyFrom(controllerContext);
- var keyIsValid = IsValid(key);
- if (keyIsValid)
- {
- UpdateValueProviderIn(controllerContext, ValueFrom(key));
- }
- return keyIsValid;
- }
- private string ButtonKeyFrom(ControllerContext controllerContext)
- {
- var keys = controllerContext.HttpContext.Request.Params.AllKeys;
- return keys.FirstOrDefault(KeyStartsWithButtonName);
- }
- private static bool IsValid(string key)
- {
- return key != null;
- }
- private static string ValueFrom(string key)
- {
- var parts = key.Split(":".ToCharArray());
- return parts.Length < 2 ? null : parts[1];
- }
- private void UpdateValueProviderIn(ControllerContext controllerContext, string value)
- {
- if (string.IsNullOrEmpty(Argument)) return;
- controllerContext.Controller.ValueProvider[Argument] = new ValueProviderResult(value, value, null);
- }
- private bool KeyStartsWithButtonName(string key)
- {
- return key.StartsWith(Name, StringComparison.InvariantCultureIgnoreCase);
- }
- }
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var key = ButtonKeyFrom(controllerContext);
var keyIsValid = IsValid(key);
if (keyIsValid)
{
UpdateValueProviderIn(controllerContext, ValueFrom(key));
}
return keyIsValid;
}
private string ButtonKeyFrom(ControllerContext controllerContext)
{
var keys = controllerContext.HttpContext.Request.Params.AllKeys;
return keys.FirstOrDefault(KeyStartsWithButtonName);
}
private static bool IsValid(string key)
{
return key != null;
}
private static string ValueFrom(string key)
{
var parts = key.Split(":".ToCharArray());
return parts.Length < 2 ? null : parts[1];
}
private void UpdateValueProviderIn(ControllerContext controllerContext, string value)
{
if (string.IsNullOrEmpty(Argument)) return;
controllerContext.Controller.ValueProvider[Argument] = new ValueProviderResult(value, value, null);
}
private bool KeyStartsWithButtonName(string key)
{
return key.StartsWith(Name, StringComparison.InvariantCultureIgnoreCase);
}
}
如果是在MVC 2.0中的话,将UpdateValueProviderIn方法改为:
- private void UpdateValueProviderIn(ControllerContext controllerContext, string value)
- {
- if (string.IsNullOrEmpty(Argument))
- return;
- controllerContext.RouteData.Values[this.Argument] = value;
- }
private void UpdateValueProviderIn(ControllerContext controllerContext, string value)
{
if (string.IsNullOrEmpty(Argument))
return;
controllerContext.RouteData.Values[this.Argument] = value;
}
转自:http://www.cnblogs.com/wuchang/archive/2010/01/29/1658916.html
MVC中实现多按钮提交(转)的更多相关文章
- 转:MVC单表多按钮提交
有时候会遇到这种情况:在一个表单上需要多个按钮来完成不同的功能,比如一个简单的审批功能. 如果是用webform那不需要讨论,但asp.net mvc中一个表单只能提交到一个Action处理,相对比较 ...
- ASP.NET MVC实现多个按钮提交事件
有时候会遇到这种情况:在一个表单上需要多个按钮来完成不同的功能,比如一个简单的审批功能. 如果是用webform那不需要讨论,但asp.net mvc中一个表单只能提交到一个Action处理,相对比较 ...
- MVC中处理表单提交的方式(Ajax+Jquery)
MVC中处理表单有很多种方法,这里说到第一种方式:Ajax+Jquery 先看下表单: <form class="row form-body form-horizontal m-t&q ...
- mvc中form表单提交的几种形式
第一种方式:submit 按钮 提交 <form action="MyDemand" method="post"> <span>关键字: ...
- MVC中获取所有按钮,并绑定事件!
<script> var btns = $('[id=addbtn]'); //不能直接使用#ID来获取,必须用[] //循环遍历所有的按钮,一个一个添加事件绑定 for (var i ...
- ASP.NET MVC中在Action获取提交的表单数据方法总结 (4种方法,转载备忘)
有Index视图如下: 视图代码如下: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Mas ...
- asp.net.mvc 中form表单提交控制器的2种方法和控制器接收页面提交数据的4种方法
MVC中表单form是怎样提交? 控制器Controller是怎样接收的? 1..cshtml 页面form提交 (1)普通方式的的提交
- ASP.NET MVC中在Action获取提交的表单数据方法
有Index视图如下: 视图代码如下: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Mas ...
- 在ASP.NET MVC中使用UEditor无法提交的解决办法
很简单的一个ajax提交,却怎么都不成功 $.ajax({ type: "POST", url: "/mms/riskmanage/commitreply", ...
随机推荐
- c++爱问的面试问题
1.static_cast,dynamic_cast,reinterpret_cast,const_cast四种转换. 2.const行为 3.malloc/free, new/delete差额 4. ...
- 微信小程序开发者工具集合包
开发论坛 http://www.henkuai.com/forum-56-1.html 工具包下载 https://yunpan.cn/ckXFpuzAeVi2s 访问密码 b4cc 开发文档 h ...
- linux 下安装jdk及配置jdk环境图解
linux 下安装jdk及配置jdk环境图解 一:先检測是否已安装了JDK 运行命令: # rpm -qa|grep jdk 或 # rpm -q jdk 或 #find / -name j ...
- [LeetCode141]Linked List Cycle
题目:Given a linked list, determine if it has a cycle in it. 判断一个链表是否有环 代码: /** * Definition for singl ...
- [LeetCode53]Maximum Subarray
问题: Find the contiguous subarray within an array (containing at least one number) which has the larg ...
- iOS编程之前
iOS编程之前 更新:帖子已经重新被更新过,以便能更好的兼容Xcode 5和iOS 7. 至今为止,已经超过6000位读者加入了这个iOS免费教程.首先,我要感谢这些加入我们社区的朋友.在 ...
- .net RPC框架选型(一)
近期开始研究分布式架构,会涉及到一个最核心的组件:RPC(Remote Procedure Call Protocol).这个东西的稳定性与性能,直接决定了分布式架构系统的好坏.RPC技术,我们的产品 ...
- SQLServer数据类型优先级对性能的影响
原文:SQLServer数据类型优先级对性能的影响 译自: http://www.mssqltips.com/sqlservertip/2749/sql-server-data-type-preced ...
- 【蓝桥杯】 PREV-1 核桃数
主题链接:http://lx.lanqiao.org/problem.page?gpid=T24 历届试题 核桃的数量 时间限制:1.0s 内存限制:256.0MB 问题描写 ...
- Meld Diff for windows 安装和配置
Meld Diff for windows 安装和配置 假设你在ubuntu 正在开发中, meld diff 此工具你肯定不会感到陌生. 而且很容易使用. 在网上看 meld for Windows ...