你如何处理 ASP.NET MVC 框架中的多个提交按钮? [英] How do you handle multiple submit buttons in ASP.NET MVC Framework?

查看:28
本文介绍了你如何处理 ASP.NET MVC 框架中的多个提交按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一些简单的方法可以处理来自同一个表单的多个提交按钮?例如:

Is there some easy way to handle multiple submit buttons from the same form? For example:

<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" value="Send" />
<input type="submit" value="Cancel" />
<% Html.EndForm(); %>

知道如何在 ASP.NET Framework Beta 中执行此操作吗?我用谷歌搜索过的所有示例都包含单个按钮.

Any idea how to do this in ASP.NET Framework Beta? All examples I've googled for have single buttons in them.

推荐答案

这里是一个基于属性的基于属性的解决方案,主要基于 Maarten Balliauw.

Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from Maarten Balliauw.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { get; set; }
    public string Argument { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        var isValidName = false;
        var keyValue = string.Format("{0}:{1}", Name, Argument);
        var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
            isValidName = true;
        }

        return isValidName;
    }
}

剃须刀:

<form action="" method="post">
 <input type="submit" value="Save" name="action:Save" />
 <input type="submit" value="Cancel" name="action:Cancel" />
</form>

和控制器:

[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }

[HttpPost]
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(MessageModel mm) { ... }

更新: Razor 页面 看起来提供了开箱即用的相同功能.对于新的开发,它可能更可取.

Update: Razor pages looks to provide the same functionality out of the box. For new development, it may be preferable.

这篇关于你如何处理 ASP.NET MVC 框架中的多个提交按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆