【MVC 5】画面マルチボタン提出

7333 ワード

画面に複数のボタンがある場合、それぞれのアクションにどのようにバインドしますか?
1.以下のMultipleButtonAttributeクラスを追加
 1 using System;
 2 using System.Reflection;
 3 using System.Web.Mvc;
 4 
 5 namespace DailyReportSystem.Attribute
 6 {
 7     [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
 8     public class MultipleButtonAttribute : ActionNameSelectorAttribute
 9     {
10         public string Name { get; set; }
11         public string Argument { get; set; }
12 
13         public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
14         {
15             var isValidName = false;
16             var keyValue = string.Format("{0}:{1}", Name, Argument);
17             var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
18 
19             if (value != null)
20             {
21                 controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
22                 isValidName = true;
23             }
24 
25             return isValidName;
26         }
27     }
28 }

2.Razor(ボタンにname属性を追加し、値のフォーマットは[{Name}:{Argument}])
<form action="" method="post">
 <input type="submit" value="Save" name="action:Save" />
 <input type="submit" value="Cancel" name="action:Cancel" />
</form>

3.Clontroller(パラメータNameとArgument対応ボタンのname属性値)
[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }

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

 原文住所:http://stackoverflow.com/questions/442704/how-do-you-handle-multiple-submit-buttons-in-asp-net-mvc-framework
 【MVC 5】ASP.NET MVCプロジェクトノート要約に追加されました