C# 如何获取控制器的按钮值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12835905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:37:48  来源:igfitidea点击:

How to get button value to controller?

c#asp.net-mvc

提问by user1348351

I have view and it has two button which are 'Yes' and 'No'. If I click 'Yes' redirect one page and if I click 'No' redirect to another page.

我有视图,它有两个按钮,分别是“是”和“否”。如果我单击“是”重定向一个页面,如果我单击“否”重定向到另一个页面。

This is my view.

这是我的看法。

@using (Html.BeginForm())
 { 
<table  >
 <tr>
    <td >
      Ceremony : 
    </td>
    <td>
       Ceremony at @Model.ceremony_date

    </td>
</tr>

  <tr>
            <td >
              Name :
            </td>
            <td >
               @Model.first_name  @Model.middle_name  @Model.last_name
            </td>
        </tr>
        <tr>
         <td colspan="2" >
            @Html.Partial("_DegreeDetailsByGraduand", @Model.DegreeList)
         </td>
        </tr>

        <tr>
        <td colspan="2" >
        IS information is correct ?
        </tr>
        <tr>
        <td>
         <input type="submit" id="btndegreeconfirmYes" name="btnsearch" class="searchbutton"  value="Yes" />    
         </td>  <td>
          <input type="submit" id="btndegreeconfirmNo" name="btnsearch" class="searchbutton"  value="No" /></td>  
        </tr>
</table>


 }

This is my controller

这是我的控制器

[HttpPost]

        public ActionResult CheckData()
        {

            return RedirectToRoute("detailform");
        }

I don't know how to get the button value in controller. How can I do it.

我不知道如何获取控制器中的按钮值。我该怎么做。

采纳答案by Mohan

Give your submit buttons a name, and then inspect the submitted value in your controller method:

为提交按钮命名,然后检查控制器方法中提交的值:

<% 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

            case "Cancel":
                // call another action to perform the cancellation

            default:
                // If they've submitted the form without a submitButton, 
                // just return the view again.
                return(View());
        }
    }

}

}

Hope this helps:

希望这可以帮助:

回答by Behnam Esmaili

use FormValueRequired attribute like this:

像这样使用 FormValueRequired 属性:

[HttpPost]
[FormValueRequired("btndegreeconfirmYes")]        
     public ActionResult CheckData()
     {
       Response.Write(submit);                    
       return RedirectToRoute("detailform");
     }

and you need to change your markup as follow:

并且您需要按如下方式更改标记:

EDIT: use two nested form

编辑:使用两个嵌套形式

    @using (Html.BeginForm())
    {
      @using (Html.BeginForm())
       {
           .
           .
           .       
      <input type="submit" id="btndegreeconfirmYes" name="btndegreeconfirmYes"class="searchbutton" value="Yes" />           
       }
<input type="submit" id="btndegreeconfirmNo" name="btndegreeconfirmNo"    class="searchbutton"  value="No" /></td>
    }

by doing this submitting form with first submit button will send only its own value and then you can use it in FromValueRquired attribute.

通过使用第一个提交按钮执行此提交表单将仅发送其自己的值,然后您可以在 FromValueRquired 属性中使用它。

回答by Diego

I supposed you are using MVC + razor engine.

我想你正在使用 MVC + 剃刀引擎。

Do like this:

这样做:

your 2 buttons:

你的 2 个按钮:

<input type="submit" value="Yes" id="buttonYes"/>
<input type="submit" value="Cancel" id="buttonCancel"/>

your form:

你的表格:

@using (Html.BeginForm("Method", "Controller", FormMethod.Post, new { enctype = "multipart/form-data", id = "CreateReportForm" }))
{ 
…
}

add this javascript to your form. Adapt your action to the action on the controller that will redirect:

将此 javascript 添加到您的表单中。使您的操作适应将重定向的控制器上的操作:

<script type="text/javascript">

    $(document).ready(function () {
        $("#buttonYes").click(function () {
            $('form#CreateReportForm').attr({ action: "Controller/Create" });
        });
        $("#buttonCancel").click(function () {
            $('form#CreateReportForm').attr({ action: " Controller /Cancel" });
        });
    });

</script>

回答by Darin Dimitrov

Try like this:

像这样尝试:

[HttpPost]
public ActionResult CheckData(string btnSearch)
{
    if (btnSearch == "Yes") {
        // The Yes submit button was clicked
    } else if (btnSearch == "No") {
        // The No submit button was clicked
    }
    return RedirectToRoute("detailform");
}

But it is usually better not to test against the text of the button but against a predefined value because the text could change and your controller action might break:

但是通常最好不要针对按钮的文本进行测试,而是针对预定义的值进行测试,因为文本可能会更改并且您的控制器操作可能会中断:

<button type="submit" name="btnsearch" value="yes">Yeah</button>
<button type="submit" name="btnsearch" value="no">Nope, I don't want to do this</button>

and then:

进而:

[HttpPost]
public ActionResult CheckData(string btnSearch)
{
    if (btnSearch == "yes") {
        // The Yes submit button was clicked
    } else if (btnSearch == "no") {
        // The No submit button was clicked
    }
    return RedirectToRoute("detailform");
}

And there's even a better approach where you could dispatch to a different controller action based on which button was clicked. Check this articleout.

还有一种更好的方法,您可以根据单击的按钮分派到不同的控制器操作。退房this article

You could have a form whose action equals to Action:

你可以有一个表单,其动作等于Action

@using (Html.BeginForm("Action", "Post")) 
{
  <input type="submit" name="saveDraft" value="Save Draft" />
  <input type="submit" name="publish" value="Publish" />
}

and then have 2 controller actions in the corresponding controller:

然后在相应的控制器中有 2 个控制器动作:

public class PostController : Controller 
{
    [HttpParamAction]
    [HttpPost]
    public ActionResult SaveDraft(...) 
    {
        // ...
    }

    [HttpParamAction]
    [HttpPost]
    public ActionResult Publish(...) 
    {
        // ...
    }
}

and here's the definition of the custom action name selector:

这是自定义操作名称选择器的定义:

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;
    }
}

Now depending on which submit button is clicked the proper controller action will be invoked.

现在,根据单击哪个提交按钮,将调用正确的控制器操作。

回答by Dije

You can create a handler so your controller can route your post according to the submit element name.

您可以创建一个处理程序,以便您的控制器可以根据提交元素名称路由您的帖子。

http://stevenbey.com/enable-multiple-submit-buttons-in-aspnet-mvc

http://stevenbey.com/enable-multiple-submit-buttons-in-aspnet-mvc

For example, a controller can handle a submit element with the name "Action_Publish" like this:

例如,控制器可以像这样处理名为“Action_Publish”的提交元素:

[HttpPost, FormAction(Prefix = "Action_")]    
public ActionResult Publish()    
{        
//...  
}