本文探討如何在同一個表單中管理多個提交按鈕。考慮以下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
接受兩個參數:Name
和 Argument
。 Name
屬性用於標識提交按鈕的名稱,而 Argument
屬性表示與該按鈕關聯的值。
要使用 MultipleButtonAttribute
,應修改表單的 HTML 代碼以包含屬性名稱和參數值。例如:
<code>(此处应插入修改后的包含属性的表单HTML代码示例)</code>
在控制器中,相應的操作方法應該用 MultipleButtonAttribute
進行裝飾,並指定正確的 Name
和 Argument
值:
<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中文網其他相關文章!