转载地址:http://www.cnblogs.com/wuchang/archive/2010/01/29/1658916.html

有时候会遇到这种情况:在一个表单上需要多个按钮来完成不同的功能,比如一个简单的审批功能。

如果是用webform那不需要讨论,但asp.net mvc中一个表单只能提交到一个Action处理,相对比较麻烦点。

方法一:使用客户端脚本

比如我们在View中这样写:

1
2
3
<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属性:

1
2
3
<input type="submit" value="审核通过" name="action" />
<input type="submit" value="审核不通过"  name="action"/>
<input type="submit" value="返回"  name="action"/>

然后在控制器中判断:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[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的选择

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[HttpPost]
[MultiButton("action1")]
public ActionResult Action1()
{
    //
    return View();
}
[HttpPost]
[MultiButton("action2")]
public ActionResult Action2()
{
    //
    return View();
}

在 View中:

1
2
3
<input type="submit" value="审核通过" name="action1" />
<input type="submit" value="审核不通过"  name="action2"/>
<input type="submit" value="返回"  name="action3"/>

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

MultiButtonAttribute的定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { getset; }
    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);
    }
}

参考:http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx

方法四、改进

Thomas Eyde就方法三的方案给出了个改进版:

Controller:

1
2
3
4
5
6
7
8
[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();
}

View:

1
2
<input type="submit" value="not important" name="delete" />
<input type="submit" value="not important" name="delete:id" />

MultiButtonAttribute定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { getset; }
    public string Argument { getset; }
 
    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方法改为:

1
2
3
4
5
6
private void UpdateValueProviderIn(ControllerContext controllerContext, string value)
{
    if (string.IsNullOrEmpty(Argument))
        return;
    controllerContext.RouteData.Values[this.Argument] = value;
}

mvc多个按钮的提交方法的更多相关文章

  1. 脚本解决.NET MVC按钮重复提交问题

    见于:Avoiding Duplicate form submission in Asp.net MVC by clicking submit twice 脚本代码: $(document).on(' ...

  2. ASP.NET MVC 5 - 查询Details和Delete方法

    在这部分教程中,接下来我们将讨论自动生成的Details和Delete方法. 查询Details和Delete方法 打开Movie控制器并查看Details方法. public ActionResul ...

  3. jsp中普通按钮如何提交表单

    jsp中普通按钮如何提交表单方法1: <form action = "提交的地址">         <input type="submit" ...

  4. Spring MVC与表单日期提交的问题

    Spring MVC与表单日期提交的问题 spring mvc 本身并不提供日期类型的解析器,需要手工绑定, 否则会出现非法参数异常. org.springframework.beans.BeanIn ...

  5. MVC 5 - 查询Details和Delete方法

    MVC 5 - 查询Details和Delete方法 在这部分教程中,接下来我们将讨论自动生成的Details和Delete方法. 查询Details和Delete方法 打开Movie控制器并查看De ...

  6. Asp.net MVC4高级编程学习笔记-模型学习第五课MVC表单和HTML辅助方法20171101

    MVC表单和HTML辅助方法 一.表单的使用. 表单中的action与method特性.Action表示表单要提交往那里,因此这里就有一个URL.这个URL可以是相对或绝对地址.表单默认的method ...

  7. [转]ASP.NET MVC 5 - 查询Details和Delete方法

    在这部分教程中,接下来我们将讨论自动生成的Details和Delete方法. 查询Details和Delete方法 打开Movie控制器并查看Details方法. public ActionResul ...

  8. jQuery实现form表单基于ajax无刷新提交方法详解

    本文实例讲述了jQuery实现form表单基于ajax无刷新提交方法.分享给大家供大家参考,具体如下: 首先,新建Login.html页面: <!DOCTYPE html PUBLIC &quo ...

  9. AJAX提交方法(POST)Demon

    AJAX的POST提交方法,本质上来看和GET差不多,有些细小的区别,POST要提交数据时,需要setRequestHeader()方法来提交HTTP头,然后send()方法中提交数据(格式为:&qu ...

随机推荐

  1. HDU 4507 吉哥系列故事——恨7不成妻

    需要推下平方和的式子..维护个数,和,平方和. #include<iostream> #include<cstdio> #include<cstring> #inc ...

  2. 【Selenium2+Python】常用操作

    Webdriver中比较常用的操作元素的方法: clear()    清除输入框的默认内容 send_keys("xxx")    在一个输入框里输入xx内容 ——如果输入中文,则 ...

  3. ecshop 常见问题汇总

    下面68ECSHOP开发中心就和大家说说ecshop使用中常见的问题 1.如何修改网站"欢迎光临本店"       回答(1) languages\zh_cn\common.php ...

  4. source insight shift+tab问题

    之前用的好好的,shift+tab功能为向左缩进(即tab的相反功能),但是突然就有问题了:现象为只是光标向左移动,但文本不动. 解决方法: 1 使用快捷键f9 2 重新定义快捷键,把shift+ta ...

  5. linux iftop流量查看工具的安装与使用

    1.安装依赖包yum install flex byacc  libpcap ncurses ncurses-devel libpcap-devel 2.下载iftop wget http://www ...

  6. POJ 3321 Apple Tree(树状数组)

                                                              Apple Tree Time Limit: 2000MS   Memory Lim ...

  7. chrome 49 版本 跨越 --args --disable-web-security --user-data-dir

    转载: 做前端的,用Ajax获取数据,是常有的事情,同域下自然没问题了,如果是不同域获取数据,浏览器就有个同源策略的限制. 如图: Origin * is not allowed by Access- ...

  8. 代理模式 (Proxy Pattern)

    代理模式的定义:为其他对象提供一种代理以控制对这个对象的访问.而对一个对象进行访问控制的一个原因是为了只有在我们确实需要这个对象时才对它进行创建和初始化.在某些情况下,一个对象不适合或者不能直接引用另 ...

  9. 综合使用union和limit区分结果并限制返回结果集的条数

    limit , 这里的limit限制了返回的union(合并)后的结果集,

  10. openfire

    wget http://download.igniterealtime.org/openfire/openfire-4.0.0-1.i386.rpm rpm -ivh openfire-4.0.0-1 ...