在ASP.NET MVC框架中處理多個提交按鈕
ASP.NET Core MVC框架允許在單個表單中使用多個提交按鈕。這提供了根據點擊的按鈕執行不同操作的靈活性。
處理多個提交按鈕的一種方法是基於屬性的路由。以下是一個示例:
屬性:
<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>
Razor視圖:
(此處應包含實際的Razor代碼,展示包含“Save”和“Cancel”兩個提交按鈕的表單。由於原文未提供,此處無法補充。)
控制器:
<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>
通過此設置,“Save”按鈕提交將調用“Save”操作,“Cancel”按鈕提交將調用“Cancel”操作。
Razor Pages的更新:
在Razor Pages中,開箱即用地提供了相同的功能。無需使用屬性,您可以使用以下語法:
(此處應包含實際的Razor Pages代碼,展示包含“Save”和“Cancel”兩個提交按鈕的表單,以及如何通過@page
指令處理。由於原文未提供,此處無法補充。)
在您的頁面處理程序中,您可以通過表單集合中的“submit-button”鍵訪問提交的按鈕值。
以上是如何處理ASP.NET MVC中的多個提交按鈕?的詳細內容。更多資訊請關注PHP中文網其他相關文章!