且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MCV4中的同一视图上使用多个按钮?

更新时间:2022-12-20 16:31:18

你可以做。检查下面提到的链接。



注意:Plz将以下代码更改为Razor





HTML



You can do it.Check below mentioned link.

Note: Plz change below code into Razor


HTML

<% using (Html.BeginForm()) {%>

       <fieldset>
           <legend>Create person</legend>
           <p>
               <%= Html.LabelFor(model => model.Name) %>
               <%= Html.TextBoxFor(model => model.Name) %>
               <%= Html.ValidationMessageFor(model => model.Name) %>
           </p>
           <p>
               <%= Html.LabelFor(model => model.Email) %>
               <%= Html.TextBoxFor(model => model.Email) %>
               <%= Html.ValidationMessageFor(model => model.Email) %>
           </p>
           <p>
               <input type="submit" value="Cancel" name="action" />
               <input type="submit" value="Create" name="action" />
           </p>
       </fieldset>

   <% } %>





控制器





Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new Person());
    }

    [HttpPost]
    [MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
    public ActionResult Cancel()
    {
        return Content("Cancel clicked");
    }

    [HttpPost]
    [MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
    public ActionResult Create(Person person)
    {
        return Content("Create clicked");
    }
}







MultiButtonAttribute类






MultiButtonAttribute class

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
    public string MatchFormKey { get; set; }
    public string MatchFormValue { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request[MatchFormKey] != null &&
            controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
    }
}





更多详情:支持ASP.NET MVC视图上的多个提交按钮







同一表格中的多个按钮



我希望这会对你有所帮助。



For more details : Supporting multiple submit buttons on an ASP.NET MVC view

OR

Multiple buttons in the same form

I hope this will help to you.