如何在MVC中使用多个提交按钮
如何在C#中的MVC中使用多个提交按钮.
how to use multiple submit button in mvc with c#.
尝试一下.您可以通过将name属性设置为所有提交按钮相同来获取button的值
Try this. You can take the value of button by setting the name attribute as same to all the submit button
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id = "submitForm" }))
{
@Html.TextBoxFor(m => m.Name, new { maxlength = 50 })
<button type="submit" id="btnSave" name="command" value="Save">Save</button>
<button type="submit" id="btnSubmit" name="command" value="Cancel"/>
}
public ActionResult Create(YourModel obj,string command)
{
//from here you can get the value of button you click
if(command="Save")
{
}
else if(command=="Cancel")
{
}
else
{
return RedirecToAction("Index");
}
return View();
}
如果要指向其他操作,请尝试此链接
http://blog. maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx [
If you want to point to different action try this link
http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx[^]
Hope this helps
尝试一下
http: //www.dotnet-tricks.com/Tutorial/mvc/cM1X161112-Handling-multiple-submit-buttons-on-the-same-form--MVC-Razor.html [
Try this
http://www.dotnet-tricks.com/Tutorial/mvc/cM1X161112-Handling-multiple-submit-buttons-on-the-same-form---MVC-Razor.html[^]
1)肮脏的一个
1) Dirty one
<input type="submit" id="Submit1" name="btnSubmit", value="action:First" />
<input type="submit" id="Submit2" name="btnSubmit", value="action:Second" />
[HttpPost]
public ActionResult MyAction(string btnSubmit, MyFormModel model)
{
switch (btnSubmit) {
case "action:First":
/* Your code */
break;
case "action:Second":
/* Your code */
break;
}
2)更好-将上面的代码重构为attribute
来自
的想法
http://blog. maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx [
2) Nicer - refactor code above to attribute
Like idea from
http://blog.maartenballiauw.be/post/2009/11/26/Supporting-multiple-submit-buttons-on-an-ASPNET-MVC-view.aspx[^]
Rephrasing code in article above:
[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);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
和您的代码
and your code
[HttpPost]
[MultipleButton(Name = "action", Argument = "First")]
public ActionResult First(MyFormModel model) { ... }
[HttpPost]
[MultipleButton(Name = "action", Argument = "Second")]
public ActionResult Second(MyFormModel model) { ... }