首页 >后端开发 >C++ >如何处理ASP.NET MVC表单中的多个提交按钮?

如何处理ASP.NET MVC表单中的多个提交按钮?

DDD
DDD原创
2025-02-01 10:51:09177浏览

How to Handle Multiple Submit Buttons in ASP.NET MVC Forms?

在ASP.NET MVC中处理多个提交按钮

本文探讨如何在同一个表单中管理多个提交按钮。考虑以下HTML代码,其中定义了一个包含两个提交按钮“发送”和“取消”的表单:

<code>(此处应插入包含两个提交按钮的表单HTML代码示例)</code>

通常,在处理ASP.NET MVC中的表单提交时,框架依靠按钮的名称来确定要执行的关联操作方法。但是,在上述多个按钮的情况下,这种方法会变得很棘手。

为了解决这个问题,本文提出了一种名为MultipleButtonAttribute的自定义属性。此属性用于拦截操作选择过程,并评估传入的请求是否源自特定的提交按钮。如果找到匹配项,则识别并调用相应的操作方法。

<code class="language-csharp">[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)
    {
        bool isValidName = false;
        string keyValue = string.Format("{0}:{1}", Name, Argument);
        ValueProviderResult value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

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

        return isValidName;
    }
}</code>

MultipleButtonAttribute 接受两个参数:NameArgumentName 属性用于标识提交按钮的名称,而 Argument 属性表示与该按钮关联的值。

要使用 MultipleButtonAttribute,应修改表单的 HTML 代码以包含属性名称和参数值。例如:

<code>(此处应插入修改后的包含属性的表单HTML代码示例)</code>

在控制器中,相应的操作方法应该用 MultipleButtonAttribute 进行装饰,并指定正确的 NameArgument 值:

<code class="language-csharp">[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }

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

使用这种方法,ASP.NET MVC 框架现在可以准确地将传入的提交按钮映射到适当的操作方法,从而允许正确处理同一表单中的多个提交按钮。

以上是如何处理ASP.NET MVC表单中的多个提交按钮?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn