public class MyController : Controller {public ActionResult MyAction(string submitButton) {switch(submitButton) {case "Send":// delegate sending to another controller actionreturn(Send());case "Cancel":// call another action to perform the cancellationreturn(Cancel());default:// If they've submitted the form without a submitButton,// just return the view again.return(View());}}
private ActionResult Cancel() {// process the cancellation request here.return(View("Cancelled"));}
private ActionResult Send() {// perform the actual send operation here.return(View("SendConfirmed"));}
}
// Note that the localized resources aren't constants, so// we can't use a switch statement.
if (submitButton == Resources.Messages.Send) {// delegate sending to another controller actionreturn(Send());
} else if (submitButton == Resources.Messages.Cancel) {// call another action to perform the cancellationreturn(Cancel());}
public class MyController : Controller{public ActionResult MyAction(string button){switch(button){case "send":this.DoSend();break;case "cancel":this.DoCancel();break;}}}
public static class FormCollectionExtensions{public static string GetSubmitButtonName(this FormCollection formCollection){return GetSubmitButtonName(formCollection, true);}
public static string GetSubmitButtonName(this FormCollection formCollection, bool throwOnError){var imageButton = formCollection.Keys.OfType<string>().Where(x => x.EndsWith(".x")).SingleOrDefault();var textButton = formCollection.Keys.OfType<string>().Where(x => x.StartsWith("Submit_")).SingleOrDefault();
if (textButton != null){return textButton.Substring("Submit_".Length);}
// we got something like AddToCart.xif (imageButton != null){return imageButton.Substring(0, imageButton.Length - 2);}
if (throwOnError){throw new ApplicationException("No button found");}else{return null;}}}
备注:对于文本按钮,您必须在名称前缀Submit_。我更喜欢这种方式,因为这意味着您可以更改文本(显示)值而无需更改代码。与SELECT元素不同,INPUT按钮只有“值”而没有单独的“文本”属性。我的按钮在不同的上下文下表示不同的内容-但映射到相同的“命令”。我更喜欢以这种方式提取名称,而不是为== "Add to cart"编码。
/// <summary>/// ActionMethodSelector to enable submit buttons to execute specific action methods./// </summary>public class AcceptParameterAttribute : ActionMethodSelectorAttribute{/// <summary>/// Gets or sets the value to use to inject the index into/// </summary>public string TargetArgument { get; set; }
/// <summary>/// Gets or sets the value to use in submit button to identify which method to select. This must be unique in each controller./// </summary>public string Action { get; set; }
/// <summary>/// Gets or sets the regular expression to match the action./// </summary>public string ActionRegex { get; set; }
/// <summary>/// Determines whether the action method selection is valid for the specified controller context./// </summary>/// <param name="controllerContext">The controller context.</param>/// <param name="methodInfo">Information about the action method.</param>/// <returns>true if the action method selection is valid for the specified controller context; otherwise, false.</returns>public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo){
if (controllerContext == null){throw new ArgumentNullException("controllerContext");}
Func<NameValueCollection> formGetter;Func<NameValueCollection> queryStringGetter;
ValidationUtility.GetUnvalidatedCollections(HttpContext.Current, out formGetter, out queryStringGetter);
var form = formGetter();var queryString = queryStringGetter();
var req = form.AllKeys.Any() ? form : queryString;
if (!string.IsNullOrEmpty(this.ActionRegex)){foreach (var key in req.AllKeys.Where(k => k.StartsWith(Action, true, System.Threading.Thread.CurrentThread.CurrentCulture))){if (key.Contains(":")){if (key.Split(':').Count() == this.ActionRegex.Split(':').Count()){bool match = false;for (int i = 0; i < key.Split(':').Count(); i++){if (Regex.IsMatch(key.Split(':')[0], this.ActionRegex.Split(':')[0])){match = true;}else{match = false;break;}}
if (match){return !string.IsNullOrEmpty(req[key]);}}}else{if (Regex.IsMatch(key, this.Action + this.ActionRegex)){return !string.IsNullOrEmpty(req[key]);}}
}return false;}else{return req.AllKeys.Contains(this.Action);}}}
//modelpublic class input_element{public string Btn { get; set; }}
//views--submit btn can be input type also...@using (Html.BeginForm()){<button type="submit" name="btn" value="verify">Verify data</button><button type="submit" name="btn" value="save">Save data</button><button type="submit" name="btn" value="redirect">Redirect</button>}
//controller
public ActionResult About(){ViewBag.Message = "Your app description page.";return View();}
[HttpPost]public ActionResult About(input_element model){if (model.Btn == "verify"){// the Verify button was clicked}else if (model.Btn == "save"){// the Save button was clicked}else if (model.Btn == "redirect"){// the Redirect button was clicked}return View();}
public ActionResult YourAction(YourModel model) {
if(Request["send"] != null) {
// we got a send
}else if(Request["cancel"]) {
// we got a cancel, but would you really want to post data for this?
}else if(Request["draft"]) {
// we got a draft
}
}
public class SubmitButtonSelector : ActionNameSelectorAttribute{public string Name { get; set; }public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo){// Try to find out if the name exists in the data sent from formvar value = controllerContext.Controller.ValueProvider.GetValue(Name);if (value != null){return true;}return false;
}}
<System.Runtime.CompilerServices.Extension()>Function ActionButton(pHtml As HtmlHelper, pAction As String, pController As String, pRouteValues As Object, pBtnValue As String, pBtnName As String, pBtnID As String) As MvcHtmlStringDim urlHelperForActionLink As UrlHelperDim btnTagBuilder As TagBuilder
Dim actionLink As StringDim onClickEventJavascript As String
urlHelperForActionLink = New UrlHelper(pHtml.ViewContext.RequestContext)If pController <> "" ThenactionLink = urlHelperForActionLink.Action(pAction, pController, pRouteValues)ElseactionLink = urlHelperForActionLink.Action(pAction, pRouteValues)End IfonClickEventJavascript = "this.form.action = '" & actionLink & "'; this.form.submit();"
btnTagBuilder = New TagBuilder("input")btnTagBuilder.MergeAttribute("type", "button")
btnTagBuilder.MergeAttribute("onClick", onClickEventJavascript)
If pBtnValue <> "" Then btnTagBuilder.MergeAttribute("value", pBtnValue)If pBtnName <> "" Then btnTagBuilder.MergeAttribute("name", pBtnName)If pBtnID <> "" Then btnTagBuilder.MergeAttribute("id", pBtnID)
Return MvcHtmlString.Create(btnTagBuilder.ToString(TagRenderMode.Normal))End Function
@helper SubmitButton(string text, string controller,string action){var uh = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);string url = @uh.Action(action, controller, null);<input type=button onclick="(function(e){$(e).parent().attr('action', '@url'); //rewrite action url//create a submit button to be clicked and removed, so that onsubmit is triggeredvar form = document.getElementById($(e).parent().attr('id'));var button = form.ownerDocument.createElement('input');button.style.display = 'none';button.type = 'submit';form.appendChild(button).click();form.removeChild(button);})(this)" value="@text"/>}
然后将其用作:
@Helpers.SubmitButton("Text for 1st button","ControllerForButton1","ActionForButton1")@Helpers.SubmitButton("Text for 2nd button","ControllerForButton2","ActionForButton2")...