[英]Can we have mutiple Submits Button in a View for different operations?
我有4個提交按鈕來執行不同的操作操作。 對於一個提交,我這樣寫
@using (Html.BeginForm("Edit", "Seller", FormMethod.Post)){
}
我們該如何處理多個“提交”按鈕? 我們是否需要為每個“提交”按鈕編寫相同的文字?
這是您為兩個提交按鈕執行的操作,類似地,您可以為“ n”個提交按鈕執行此操作。
下面是帶有兩個提交按鈕的表單。 請注意,這兩個提交按鈕的名稱相同,即“ submitButton”
@Html.BeginForm("MyAction", "MyController"); %>
<input type="submit" name="submitButton" value="Button1" />
<input type="submit" name="submitButton" value="Button2" />
}
現在到Controller,Action接受一個名為string stringButton的輸入參數,其余參數很不言自明。
public ActionResult MyAction(string submitButton) {
switch(submitButton) {
case "Button1":
// do something here
case "Button2":
// do some other thing here
default:
// add some other behaviour here
}
...
}
我在這種用例中使用MultiButtonAttribute。 很好,很清楚。 您可以將邏輯分為不同的操作方法。
MulitButtonAttribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public MultiButtonAttribute(string matchFormKey) : this(matchFormKey, null) {
}
public MultiButtonAttribute(string matchFormKey, string matchFormValue) {
this.MatchFormKey = matchFormKey;
this.MatchFormValue = matchFormValue;
}
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
string value = controllerContext.HttpContext.Request[MatchFormKey];
return value != null && (value == MatchFormValue || MatchFormValue == null);
}
}
在控制器中
[HttpPost]
[MultiButton("buttonPreviousPage")]
public ActionResult NavigateToPreviousPage(int currentPageIndex)
{
// .. action logic
}
視野中
@using (Html.BeginForm("SomeDefaultAction", "MyController", FormMethod.Post)){
<input type="submit" id="buttonPreviousPage" name="buttonPreviousPage" value="Previous" />
<input type="submit" id="buttonNextPage" name="buttonNextPage" value="Next" />
}
這個怎么運作
MultiButtonAttribute
擴展ActionNameSelectorAttribute
很重要。 當MVC選擇正確的方法來匹配路由時,它將在方法上找到這樣的屬性,它將通過ControllerContext
在屬性上調用IsValidName
方法。 它正在查看鍵(按鈕名稱)是否為POSTed形式,並且不具有空值(或者最終您可以定義鍵(按鈕)的期望值,但這不是必需的)。
在MVC 2中效果很好(但我希望它能在以后的版本中使用)。 另一個優點是您可以本地化按鈕的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.