是否有一些简单的方法来处理来自同一个表单的多个提交按钮?例如:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" value="Send" />
<input type="submit" value="Cancel" />
<% Html.EndForm(); %>
知道如何在ASP中做到这一点吗?NET框架测试版?我在谷歌上搜索的所有例子中都有单个按钮。
是否有一些简单的方法来处理来自同一个表单的多个提交按钮?例如:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" value="Send" />
<input type="submit" value="Cancel" />
<% Html.EndForm(); %>
知道如何在ASP中做到这一点吗?NET框架测试版?我在谷歌上搜索的所有例子中都有单个按钮。
你可以这样写:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="button" value="Send" />
<input type="submit" name="button" value="Cancel" />
<% Html.EndForm(); %>
然后在页面中检查name == "Send"或者name == "Cancel"…
您可以像前面提到的那样检查动作中的名称,但是您可能会考虑这是否是好的设计。考虑动作的职责,不要将这种设计过多地与按钮名称等UI方面结合起来,这是一个好主意。所以考虑使用两种形式和两种动作:
<% Html.BeginForm("Send", "MyController", FormMethod.Post); %>
<input type="submit" name="button" value="Send" />
<% Html.EndForm(); %>
<% Html.BeginForm("Cancel", "MyController", FormMethod.Post); %>
<input type="submit" name="button" value="Cancel" />
<% Html.EndForm(); %>
此外,在“取消”的情况下,您通常只是不处理表单,而是转到一个新的URL。在这种情况下,你根本不需要提交表单,只需要一个链接:
<%=Html.ActionLink("Cancel", "List", "MyController") %>
给你的提交按钮一个名字,然后在你的控制器方法中检查提交的值:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="Send" />
<input type="submit" name="submitButton" value="Cancel" />
<% Html.EndForm(); %>
发布到
public class MyController : Controller {
public ActionResult MyAction(string submitButton) {
switch(submitButton) {
case "Send":
// delegate sending to another controller action
return(Send());
case "Cancel":
// call another action to perform the cancellation
return(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"));
}
}
编辑:
要将此方法扩展到本地化站点,请将您的消息隔离在其他地方(例如将资源文件编译为强类型资源类)
然后修改代码,使其像这样工作:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="<%= Html.Encode(Resources.Messages.Send)%>" />
<input type="submit" name="submitButton" value="<%=Html.Encode(Resources.Messages.Cancel)%>" />
<% Html.EndForm(); %>
你的控制器应该是这样的:
// 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 action
return(Send());
} else if (submitButton == Resources.Messages.Cancel) {
// call another action to perform the cancellation
return(Cancel());
}
Eilon建议你可以这样做:
If you have more than one button you can distinguish between them by giving each button a name: <input type="submit" name="SaveButton" value="Save data" /> <input type="submit" name="CancelButton" value="Cancel and go back to main page" /> In your controller action method you can add parameters named after the HTML input tag names: public ActionResult DoSomeStuff(string saveButton, string cancelButton, ... other parameters ...) { ... } If any value gets posted to one of those parameters, that means that button was the one that got clicked. The web browser will only post a value for the one button that got clicked. All other values will be null. if (saveButton != null) { /* do save logic */ } if (cancelButton != null) { /* do cancel logic */ }
我喜欢这个方法,因为它不依赖于提交按钮的值属性,这个属性比分配的名称更有可能改变,并且不需要启用javascript
看到的: http://forums.asp.net/p/1369617/2865166.aspx#2865166
David Findley在他的ASP上写了3种不同的选择。网络博客。
阅读文章的多个按钮以相同的形式查看他的解决方案,以及每个方案的优缺点。恕我直言,他提供了一个非常优雅的解决方案,利用属性,你装饰你的行动。
刚刚写了一篇相关的文章: 多个提交按钮与ASP。NET MVC:
基本上,我用的不是ActionMethodSelectorAttribute,而是 ActionNameSelectorAttribute,它允许我假装动作名是我想要的任何东西。幸运的是,ActionNameSelectorAttribute不只是让我指定操作名称,而是我可以选择当前操作是否与请求匹配。
这就是我的班级(顺便说一句,我不太喜欢这个名字):
public class HttpParamActionAttribute : ActionNameSelectorAttribute {
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
return false;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
只需要像这样定义一个表单:
<% using (Html.BeginForm("Action", "Post")) { %>
<!— …form fields… -->
<input type="submit" name="saveDraft" value="Save Draft" />
<input type="submit" name="publish" value="Publish" />
<% } %>
控制器有两个方法
public class PostController : Controller {
[HttpParamAction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveDraft(…) {
//…
}
[HttpParamAction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Publish(…) {
//…
}
}
如您所见,该属性根本不需要指定任何内容。此外,按钮的名称直接转换为方法名称。此外(我还没有尝试过)这些应该作为正常的动作以及,所以你可以张贴到他们中的任何一个 直接。
我建议感兴趣的人看看Maarten Balliauw的解决方案。我认为它非常优雅。
如果链接消失,它将使用应用于控制器操作的MultiButton属性来指示该操作应该与哪个按钮单击相关。
这是我使用的技巧,但我在这里还没有看到。链接(由Saajid Ismail发布 )启发这个解决方案的是http://weblogs.asp.net/dfindley/archive/2009/05/31/asp-net-mvc-multiple-buttons-in-the-same-form.aspx)。它适应Dylan Beattie的答案做本地化没有任何问题。
在视图中:
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<button name="button" value="send"><%: Resources.Messages.Send %></button>
<button name="button" value="cancel"><%: Resources.Messages.Cancel %></button>
<% Html.EndForm(); %>
在控制器中:
public class MyController : Controller
{
public ActionResult MyAction(string button)
{
switch(button)
{
case "send":
this.DoSend();
break;
case "cancel":
this.DoCancel();
break;
}
}
}
下面是我写的一个扩展方法来处理多个图像和/或文本按钮。
下面是一个图片按钮的HTML:
<input id="btnJoin" name="Join" src="/content/images/buttons/btnJoin.png"
type="image">
或者对于文本提交按钮:
<input type="submit" class="ui-button green" name="Submit_Join" value="Add to cart" />
<input type="submit" class="ui-button red" name="Submit_Skip" value="Not today" />
下面是使用form.GetSubmitButtonName()从控制器调用的扩展方法。对于图像按钮,它查找带有.x的表单参数(表示单击了图像按钮)并提取名称。对于常规输入按钮,它查找以Submit_开头的名称并从中提取命令。因为我抽象了确定“命令”的逻辑,所以你可以在客户端上切换图像+文本按钮,而无需更改服务器端代码。
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.x
if (imageButton != null)
{
return imageButton.Substring(0, imageButton.Length - 2);
}
if (throwOnError)
{
throw new ApplicationException("No button found");
}
else
{
return null;
}
}
}
注意:对于文本按钮,必须在名称前加上Submit_。我更喜欢这种方式,因为这意味着您可以更改文本(显示)值,而不必更改代码。与SELECT元素不同,INPUT按钮只有一个“value”,没有单独的“text”属性。我的按钮在不同的上下文中表示不同的内容-但映射到相同的“命令”。我更喜欢以这种方式提取名称,而不是必须为==“Add to cart”编码。
视图中的代码是:
<script language="javascript" type="text/javascript">
function SubmeterForm(id)
{
if (id=='btnOk')
document.forms[0].submit(id);
else
document.forms[1].submit(id);
}
</script>
<% Html.BeginForm("ObterNomeBotaoClicado/1", "Teste01", FormMethod.Post); %>
<input id="btnOk" type="button" value="Ok" onclick="javascript:SubmeterForm('btnOk')" />
<% Html.EndForm(); %>
<% Html.BeginForm("ObterNomeBotaoClicado/2", "Teste01", FormMethod.Post); %>
<input id="btnCancelar" type="button" value="Cancelar" onclick="javascript:SubmeterForm('btnCancelar')" />
<% Html.EndForm(); %>
在Controller中,代码是:
public ActionResult ObterNomeBotaoClicado(string id)
{
if (id=="1")
btnOkFunction(...);
else
btnCancelarFunction(...);
return View();
}
下面是基于Maarten Balliauw的帖子和评论,针对多个提交按钮问题的一个非常干净的基于属性的解决方案。
[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)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
剃须刀:
<form action="" method="post">
<input type="submit" value="Save" name="action:Save" />
<input type="submit" value="Cancel" name="action:Cancel" />
</form>
和控制器:
[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }
[HttpPost]
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(MessageModel mm) { ... }
更新:Razor页面提供相同的功能开箱即用。对于新的开发来说,它可能更可取。
我的JQuery方法使用扩展方法:
public static MvcHtmlString SubmitButtonFor<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string value) where TController : Controller
{
RouteValueDictionary routingValues = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);
var onclick = string.Format("$('form').first().attr('action', '/{0}')", string.Join("/", routingValues.Values.ToArray().Where(x => x != null).Select(x => x.ToString()).ToArray()));
var html = "<input type=\"submit\" value=\"" + value + "\" onclick=\"" + onclick + "\" />";
return MvcHtmlString.Create(html);
}
你可以这样使用它:
@(Html.SubmitButtonFor<FooController>(c => c.Save(null), "Save"))
它是这样渲染的:
<input type="submit" value="Save" onclick="$('form').first().attr('action', '/Foo/Save')" >
如果你对HTML 5的使用没有限制,你可以使用带有formaction的<button>标签:
<form action="demo_form.asp" method="get">
First name: <input type="text" name="fname" /><br />
Last name: <input type="text" name="lname" /><br />
<button type="submit">Submit</button><br />
<button type="submit" formaction="demo_admin.asp">Submit as admin</button>
</form>
参考:http://www.w3schools.com/html5/att_button_formaction.asp
这是我发现的最好的方法:
http://iwayneo.blogspot.co.uk/2013/10/aspnet-mvc-action-selector-with-list.html
代码如下:
/// <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);
}
}
}
享受一个没有代码气味的多提交按钮的未来。
谢谢你!
以下是最适合我的方法:
<input type="submit" value="Delete" name="onDelete" />
<input type="submit" value="Save" name="onSave" />
public ActionResult Practice(MyModel model, string onSave, string onDelete)
{
if (onDelete != null)
{
// Delete the object
...
return EmptyResult();
}
// Save the object
...
return EmptyResult();
}
我的解决方案是使用2个asp面板:
< asp:面板ID = " . . "DefaultButton = " ID_OF_SHIPPING_SUBMIT_BUTTON "…> < / asp:面板>
这个脚本允许指定一个data-form-action属性,它将在所有浏览器中作为HTML5 formaction属性(以一种不引人注目的方式):
$(document).on('click', '[type="submit"][data-form-action]', function(event) {
var $this = $(this),
var formAction = $this.attr('data-form-action'),
$form = $($this.closest('form'));
$form.attr('action', formAction);
});
包含按钮的表单将被发送到data-form-action属性中指定的URL:
<button type="submit" data-form-action="different/url">Submit</button>
这需要jQuery 1.7。对于以前的版本,您应该使用live()而不是on()。
对于每个提交按钮,只需添加:
$('#btnSelector').click(function () {
$('form').attr('action', "/Your/Action/);
$('form').submit();
});
我尝试综合所有的解决方案,并创建了一个[ButtenHandler]属性,它可以很容易地处理表单上的多个按钮。
我已经在CodeProject中描述了它在ASP中的多个参数化(本地化)表单按钮。净MVC。
要处理此按钮的简单情况:
<button type="submit" name="AddDepartment">Add Department</button>
你会有如下的动作方法:
[ButtonHandler()]
public ActionResult AddDepartment(Company model)
{
model.Departments.Add(new Department());
return View(model);
}
注意按钮的名称与动作方法的名称是如何匹配的。本文还描述了如何让按钮具有值和按钮具有索引。
我没有足够的代表在正确的地方发表评论,但我花了一整天的时间在这上面,所以想分享。
在尝试实现“MultipleButtonAttribute”解决方案时,ValueProvider.GetValue(keyValue)将错误地返回null。
原来我引用的是System.Web.MVC版本3.0,而它应该是4.0(其他程序集是4.0)。我不知道为什么我的项目没有正确升级,我没有其他明显的问题。
所以如果你的ActionNameSelectorAttribute不工作…检查。
//model
public 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();
}
基于mkozicki的答案,我提出了一个有点不同的解决方案。我仍然使用ActionNameSelectorAttribute,但我需要处理两个按钮“保存”和“同步”。它们做的几乎是一样的,所以我不想有两个动作。
属性:
public class MultipleButtonActionAttribute : ActionNameSelectorAttribute
{
private readonly List<string> AcceptedButtonNames;
public MultipleButtonActionAttribute(params string[] acceptedButtonNames)
{
AcceptedButtonNames = acceptedButtonNames.ToList();
}
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
foreach (var acceptedButtonName in AcceptedButtonNames)
{
var button = controllerContext.Controller.ValueProvider.GetValue(acceptedButtonName);
if (button == null)
{
continue;
}
controllerContext.Controller.ControllerContext.RouteData.Values.Add("ButtonName", acceptedButtonName);
return true;
}
return false;
}
}
view
<input type="submit" value="Save" name="Save" />
<input type="submit" value="Save and Sync" name="Sync" />
控制器
[MultipleButtonAction("Save", "Sync")]
public ActionResult Sync(OrgSynchronizationEditModel model)
{
var btn = this.RouteData.Values["ButtonName"];
我还想指出,如果动作做不同的事情,我可能会遵循mkozicki的帖子。
Modified version of HttpParamActionAttribute method but with a bug fix for not causing an error on expired/invalid session postbacks. To see if this is a problem with your current site, open the your form in a window and just before you go to click Save or Publish, open a duplicate window, and logout. Now go back to your first window and try to submit your form using either button. For me I got an error so this change solves that problem for me. I omit a bunch of stuff for the sake of brevity but you should get the idea. The key parts are the inclusion of ActionName on the attribute and making sure the name passed in is the name of the View that shows the form
属性类
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
private readonly string actionName;
public HttpParamActionAttribute(string actionName)
{
this.actionName = actionName;
}
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
if (!actionName.Equals(this.actionName, StringComparison.InvariantCultureIgnoreCase))
return false;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
控制器
[Authorize(Roles="CanAddContent")]
public ActionResult CreateContent(Guid contentOwnerId)
{
var viewModel = new ContentViewModel
{
ContentOwnerId = contentOwnerId
//populate rest of view model
}
return View("CreateContent", viewModel);
}
[Authorize(Roles="CanAddContent"), HttpPost, HttpParamAction("CreateContent"), ValidateAntiForgeryToken]
public ActionResult SaveDraft(ContentFormModel model)
{
//Save as draft
return RedirectToAction("CreateContent");
}
[Authorize(Roles="CanAddContent"), HttpPost, HttpParamAction("CreateContent"), ValidateAntiForgeryToken]
public ActionResult Publish(ContentFormModel model)
{
//publish content
return RedirectToAction("CreateContent");
}
View
@using (Ajax.BeginForm("CreateContent", "MyController", new { contentOwnerId = Model.ContentOwnerId }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => x.ContentOwnerId)
<!-- Rest of your form controls -->
<input name="SaveDraft" type="submit" value="SaveDraft" />
<input name="Publish" type="submit" value="Publish" />
}
我不喜欢ActionSelectName的地方是IsValidName被控制器中的每个动作方法调用;我不知道为什么会这样。我喜欢一种解决方案,每个按钮都有一个不同的名称,基于它的功能,但我不喜欢这样的事实,你必须有许多参数在动作方法中的按钮在表单。我已经为所有按钮类型创建了一个枚举:
public enum ButtonType
{
Submit,
Cancel,
Delete
}
而不是ActionSelectName,我使用ActionFilter:
public class MultipleButtonsEnumAttribute : ActionFilterAttribute
{
public Type EnumType { get; set; }
public MultipleButtonsEnumAttribute(Type enumType)
{
EnumType = enumType;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
foreach (var key in filterContext.HttpContext.Request.Form.AllKeys)
{
if (Enum.IsDefined(EnumType, key))
{
var pDesc = filterContext.ActionDescriptor.GetParameters()
.FirstOrDefault(x => x.ParameterType == EnumType);
filterContext.ActionParameters[pDesc.ParameterName] = Enum.Parse(EnumType, key);
break;
}
}
}
}
过滤器将在表单数据中找到按钮名称,如果按钮名称与枚举中定义的任何按钮类型匹配,它将在动作参数中找到ButtonType参数:
[MultipleButtonsEnumAttribute(typeof(ButtonType))]
public ActionResult Manage(ButtonType buttonPressed, ManageViewModel model)
{
if (button == ButtonType.Cancel)
{
return RedirectToAction("Index", "Home");
}
//and so on
return View(model)
}
然后在视图中,我可以使用:
<input type="submit" value="Button Cancel" name="@ButtonType.Cancel" />
<input type="submit" value="Button Submit" name="@ButtonType.Submit" />
如果您的浏览器支持输入按钮的属性格式操作(IE 10+,不确定其他浏览器),那么以下应该工作:
@using (Html.BeginForm()){
//put form inputs here
<input id="sendBtn" value="Send" type="submit" formaction="@Url.Action("Name Of Send Action")" />
<input id="cancelBtn" value="Cancel" type="submit" formaction="@Url.Action("Name of Cancel Action") />
}
我也遇到过这个“问题”,但通过添加name属性找到了一个相当合理的解决方案。我不记得在其他语言中有这个问题。
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2
... 如果表单包含多个提交按钮,则只有激活的提交按钮是成功的。 ...
这意味着以下代码值属性可以被更改、本地化、国际化,而不需要额外的代码检查强类型资源文件或常量。
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="send" value="Send" />
<input type="submit" name="cancel" value="Cancel" />
<input type="submit" name="draft" value="Save as draft" />
<% Html.EndForm(); %>`
在接收端,您只需要检查是否有任何已知的提交类型不是空
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
}
}
Index.cshtml @using (Html.BeginForm(“Index”, “Home”, FormMethod.Post, new { id = “submitForm” })) { 按钮类型=“提交” id=“btn批准” 名称=“命令” 值=“批准”>批准 按钮类型=“提交” id=“btn拒绝” 名称=“命令” 值=“拒绝”>拒绝 }
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection frm, string Command)
{
if (Command == "Approve")
{
}
else if (Command == "Reject")
{
}
return View();
}
}
当使用ajax表单时,我们可以使用ActionLinks与POST HttpMethod和 在AjaxOptions中序列化表单。OnBegin事件。
假设你有两个动作,InsertAction和UpdateAction:
<form>
@Html.Hidden("SomeField", "SomeValue")
@Ajax.ActionLink(
"Insert",
"InsertAction",
null,
new AjaxOptions {
OnBegin = "OnBegin",
UpdateTargetId = "yourDiv",
HttpMethod = "POST" })
@Ajax.ActionLink(
"Update",
"UpdateAction",
null,
new AjaxOptions {
OnBegin = "OnBegin",
UpdateTargetId = "yourDiv",
HttpMethod = "POST" })
</form>
Javascript
function OnBegin(xhr, settings) {
settings.data = $("form").serialize();
}
有三种方法可以解决上述问题
HTML的方式 Jquery的方式 “ActionNameSelectorAttribute”的方式
下面是一个视频,它以演示的方式总结了所有三种方法。
https://www.facebook.com/shivprasad.koirala/videos/vb.100002224977742/809335512483940
HTML方式:-
在HTML中,我们需要创建两个表单,并在每个表单中放置“Submit”按钮。每一种形式的动作都会指向不同的/各自的动作。你可以看到下面的代码,第一个表单发布到“Action1”,第二个表单将发布到“Action2”,这取决于点击哪个“提交”按钮。
<form action="Action1" method=post>
<input type=”submit” name=”Submit1”/>
</form>
<form action="Action2" method=post>
<input type=”submit” name=”Submit2”>
</form>
Ajax方式:-
如果您是Ajax爱好者,那么第二个选项会让您更兴奋。在Ajax中,我们可以创建两个不同的函数“Fun1”和“Fun1”,参见下面的代码。这些函数将使用JQUERY或任何其他框架进行Ajax调用。这些函数都与“Submit”按钮的“OnClick”事件绑定。每个函数都调用各自的动作名。
<Script language="javascript">
function Fun1()
{
$.post(“/Action1”,null,CallBack1);
}
function Fun2()
{
$.post(“/Action2”,null,CallBack2);
}
</Script>
<form action="/Action1" method=post>
<input type=submit name=sub1 onclick=”Fun2()”/>
</form>
<form action="/Action2" method=post>
<input type=submit name=sub2 onclick=”Fun1()”/>
</form>
使用“ActionNameSelectorAttribute”:-
这是一个很好的干净的选择。“ActionNameSelectorAttribute”是一个简单的属性类,我们可以在其中编写决策逻辑,该逻辑将决定可以执行哪些操作。
首先在HTML中,我们需要给提交按钮设置正确的名称以便在服务器上识别它们。
你可以看到我们把“保存”和“删除”放在按钮名称上。你还可以注意到,在动作中,我们只是把控制器名“Customer”,而不是一个特定的动作名。我们期望动作名称将由“ActionNameSelectorAttribute”决定。
<form action=”Customer” method=post>
<input type=submit value="Save" name="Save" /> <br />
<input type=submit value="Delete" name="Delete"/>
</form>
因此,当单击提交按钮时,它首先命中“ActionNameSelector”属性,然后根据触发的提交调用适当的操作。
因此,第一步是创建一个继承自“ActionNameSelectorAttribute”类的类。在这个类中,我们创建了一个简单的属性“Name”。
我们还需要重写返回true或flase的“IsValidName”函数。无论是否执行某个操作,我们都要在这个函数中编写逻辑。因此,如果这个函数返回true,则执行动作,否则不执行。
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 form
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
{
return true;
}
return false;
}
}
上述函数的核心在下面的代码中。“ValueProvider”集合包含从表单中发布的所有数据。因此,它首先查找“Name”值,如果在HTTP请求中找到它,则返回true,否则返回false。
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
{
return true;
}
return false;
然后可以在各自的操作上装饰这个属性类,并提供各自的“Name”值。因此,如果提交正在命中这个动作,如果名称与HTML提交按钮名称匹配,则进一步执行该动作,否则不执行。
public class CustomerController : Controller
{
[SubmitButtonSelector(Name="Save")]
public ActionResult Save()
{
return Content("Save Called");
}
[SubmitButtonSelector(Name = "Delete")]
public ActionResult Delete()
{
return Content("Delete Called");
}
}
我已经为HtmlHelper创建了一个ActionButton方法。它将在OnClick事件中生成带有javascript的普通输入按钮,将表单提交给指定的控制器/动作。
像这样使用辅助器
@Html.ActionButton("MyControllerName", "MyActionName", "button text")
这将生成以下HTML
<input type="button" value="button text" onclick="this.form.action = '/MyWebsiteFolder/MyControllerName/MyActionName'; this.form.submit();">
下面是扩展方法代码:
VB。网
<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 MvcHtmlString
Dim urlHelperForActionLink As UrlHelper
Dim btnTagBuilder As TagBuilder
Dim actionLink As String
Dim onClickEventJavascript As String
urlHelperForActionLink = New UrlHelper(pHtml.ViewContext.RequestContext)
If pController <> "" Then
actionLink = urlHelperForActionLink.Action(pAction, pController, pRouteValues)
Else
actionLink = urlHelperForActionLink.Action(pAction, pRouteValues)
End If
onClickEventJavascript = "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
c# (c#代码只是从VB DLL中反编译的,所以它可以得到一些美化…但是时间太短了:-)
public static MvcHtmlString ActionButton(this HtmlHelper pHtml, string pAction, string pController, object pRouteValues, string pBtnValue, string pBtnName, string pBtnID)
{
UrlHelper urlHelperForActionLink = new UrlHelper(pHtml.ViewContext.RequestContext);
bool flag = Operators.CompareString(pController, "", true) != 0;
string actionLink;
if (flag)
{
actionLink = urlHelperForActionLink.Action(pAction, pController, System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(pRouteValues));
}
else
{
actionLink = urlHelperForActionLink.Action(pAction, System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(pRouteValues));
}
string onClickEventJavascript = "this.form.action = '" + actionLink + "'; this.form.submit();";
TagBuilder btnTagBuilder = new TagBuilder("input");
btnTagBuilder.MergeAttribute("type", "button");
btnTagBuilder.MergeAttribute("onClick", onClickEventJavascript);
flag = (Operators.CompareString(pBtnValue, "", true) != 0);
if (flag)
{
btnTagBuilder.MergeAttribute("value", pBtnValue);
}
flag = (Operators.CompareString(pBtnName, "", true) != 0);
if (flag)
{
btnTagBuilder.MergeAttribute("name", pBtnName);
}
flag = (Operators.CompareString(pBtnID, "", true) != 0);
if (flag)
{
btnTagBuilder.MergeAttribute("id", pBtnID);
}
return MvcHtmlString.Create(btnTagBuilder.ToString(TagRenderMode.Normal));
}
这些方法具有各种参数,但是为了便于使用,您可以创建一些重载,只使用所需的参数。
我来派对已经很晚了,但现在开始… 我的实现借用了@mkozicki,但需要更少的硬编码字符串来出错。需要4.5+框架。实际上,控制器方法名应该是路由的关键。
标记。按钮名称必须以“action:[controllerMethodName]”为键
(注意使用c# 6的API名称,提供了对希望调用的控制器方法名称的特定类型引用。
<form>
... form fields ....
<button name="action:@nameof(MyApp.Controllers.MyController.FundDeathStar)" type="submit" formmethod="post">Fund Death Star</button>
<button name="action:@nameof(MyApp.Controllers.MyController.HireBoba)" type="submit" formmethod="post">Hire Boba Fett</button>
</form>
控制器:
namespace MyApp.Controllers
{
class MyController
{
[SubmitActionToThisMethod]
public async Task<ActionResult> FundDeathStar(ImperialModel model)
{
await TrainStormTroopers();
return View();
}
[SubmitActionToThisMethod]
public async Task<ActionResult> HireBoba(ImperialModel model)
{
await RepairSlave1();
return View();
}
}
}
属性的魔法。注意使用CallerMemberName功能。
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class SubmitActionToThisMethodAttribute : ActionNameSelectorAttribute
{
public SubmitActionToThisMethodAttribute([CallerMemberName]string ControllerMethodName = "")
{
controllerMethod = ControllerMethodName;
actionFormat = string.Concat(actionConstant, ":", controllerMethod);
}
const string actionConstant = "action";
readonly string actionFormat;
readonly string controllerMethod;
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var value = controllerContext.Controller.ValueProvider.GetValue(actionFormat);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[actionConstant] = controllerMethod;
isValidName = true;
}
return isValidName;
}
}
使用自定义助手(创建一个“Helpers.”文件)。cshtml" App_Code文件夹内,在你的项目的根)用javascript重写(在一个'onclick'事件)表单的'动作'属性,你想要的东西,然后提交它。
助手可以是这样的:
@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 triggered
var 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")
...
在你的表单里面。
它短小而紧凑:
Jeroen Dop回答了这个问题
<input type="submit" name="submitbutton1" value="submit1" />
<input type="submit" name="submitbutton2" value="submit2" />
在后面的代码中这样做
if( Request.Form["submitbutton1"] != null)
{
// Code for function 1
}
else if(Request.Form["submitButton2"] != null )
{
// code for function 2
}
祝你好运。
[HttpPost]
public ActionResult ConfirmMobile(string nameValueResend, string nameValueSubmit, RegisterModel model)
{
var button = nameValueResend ?? nameValueSubmit;
if (button == "Resend")
{
}
else
{
}
}
Razor file Content:
@using (Html.BeginForm()
{
<div class="page registration-result-page">
<div class="page-title">
<h1> Confirm Mobile Number</h1>
</div>
<div class="result">
@Html.EditorFor(model => model.VefificationCode)
@Html.LabelFor(model => model.VefificationCode, new { })
@Html.ValidationMessageFor(model => model.VefificationCode)
</div>
<div class="buttons">
<button type="submit" class="btn" name="nameValueResend" value="Resend">
Resend
</button>
<button type="submit" class="btn" name="nameValueSubmit" value="Verify">
Submit
</button>
</div>
</div>
}