MVC 5在一个视图上提交多个

gil*_*rpa 6 c# asp.net-mvc asp.net-mvc-4

我知道这已经被问过多次了。但是到目前为止,我还没有找到可行的解决方案。

我在视图中有以下代码:

@using (Html.BeginForm("RoleEdit", "AccountRoles", FormMethod.Post, new { id = "updaterole" }))
{
    <button name="mySubmit" formaction="@Url.Action("SetDefaultRole", "AccountRoles")" value="MakeDefault" class="button small">Make Default</button>

    ...


    other code

    ...

    <button type="submit" class="button small" value="save" name="save" id="save">@Resources.DashBoardTags.UpdateRoleTag</button>
}
Run Code Online (Sandbox Code Playgroud)

并在控制器中:

   [HttpPost]
    public ActionResult SetDefaultRole()
    {

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

和:

    [HttpPost]
    public ActionResult RoleEdit(List<UserRole> userRole, string mySubmit)
    {

        if (mySubmit == "Save Draft")
        {
            //save draft code here
        }
        else if (mySubmit == "Publish")
        {
            //publish code here
        }
     }
Run Code Online (Sandbox Code Playgroud)

当代码执行时:

  1. 当单击第一个提交按钮时,它将忽略SetDefaultRole函数并执行RoleEdit函数。

  2. RoleEdit函数的值mySubmit为空。

请向我展示我的方式的错误!!!

我看了建议的解决方案:建议的解决方案

由此,我创建了一个名为MultipleButton的属性扩展,并更改了代码,以使代码现在看起来像这样:

视图:

@using (Html.BeginForm("RoleEdit", "AccountRoles", FormMethod.Post, new { id = "updaterole" }))
{
   <button value="SetDefaultRole" name="action:SetDefaultRole" class="button small" formmethod="post">Make Default</button>

    ...


    other code

    ...

    <button value="RoleEdit" name="mySubmit:RoleEdit" class="button small" formmethod="post">@Resources.DashBoardTags.UpdateRoleTag</button>
}
Run Code Online (Sandbox Code Playgroud)

控制者

    [HttpPost]
    [MultipleButton(Name= "action", Argument = "SetDefaultRole")]
    public ActionResult SetDefaultRole()
    {

        return View();
    }

    [HttpPost]
    [MultipleButton(Name = "action", Argument = "RoleEdit")]
    public ActionResult RoleEdit(List<UserRole> userRole)
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

在新扩展中,上面提议的解决方案链接中显示的MultipleButtonAttribute被执行,下面的代码行始终返回空值:

controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
Run Code Online (Sandbox Code Playgroud)

谁能帮忙。

Kin*_*hil 4

您可以从名称标签中识别您的按钮,如下所示,您需要在控制器中进行这样的检查

if (Request.Form["mySubmit"] != null)
{
//Write your code here
}
else if (Request.Form["save"] != null)
{
//Write your code here
}
Run Code Online (Sandbox Code Playgroud)

或者尝试;

[HttpPost]
    public ActionResult RoleEdit(List<UserRole> userRole, FormCollection fc)
    {

        if (fc["mySubmit"] != null)
        {
            //save draft code here
        }
        else if (fc["mySubmit"] != null)
        {
            //publish code here
        }
     }
Run Code Online (Sandbox Code Playgroud)