【问题标题】:How to send data from view to controller on button click如何在按钮单击时将数据从视图发送到控制器
【发布时间】:2013-06-21 13:31:29
【问题描述】:

如何在单击按钮时调用控制器操作并及时发送下拉列表中选择的值?这是我的 .cshtml 的外观示例。这只是一个例子,一般我需要在按钮被点击的时候及时从当前视图中收集很多数据。

<body>
    <div>
        @Html.DropDownList("Name")
        <br />
        @Html.DropDownList("Age")
        <br />
        @Html.DropDownList("Gender")
        <br />
        @using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post))
        {
            <input type="submit" value="Find" />
        }
    </div>
</body>

【问题讨论】:

  • 这似乎是一个非常基本的问题 - 您是否尝试过寻找教程?

标签: c# asp.net-mvc asp.net-mvc-4 razor razor-2


【解决方案1】:

为了将数据提交给控制器,输入必须出现在&lt;form&gt; 标记内。

例如:

<body>
    <div>
        @using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post))
        {

            @Html.DropDownList("Name")
            <br />
            @Html.DropDownList("Age")
            <br />
            @Html.DropDownList("Gender")
            <br />
            <input type="submit" value="Find" />
        }
    </div>
</body>

【讨论】:

  • 谢谢。为了帮助其他人如何在控制器中使用它: public ActionResult FindPerson(FormCollection form)
【解决方案2】:

在@using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post)) 中,您应该输入您的输入。

你在表单之外有你的输入

@using (Html.BeginForm("FindPerson", "MyController", FormMethod.Post))
    {
    @Html.DropDownList("Name")
    <br />
    @Html.DropDownList("Age")
    <br />
    @Html.DropDownList("Gender")
    <br />

        <input type="submit" value="Find" />
}

【讨论】:

    【解决方案3】:

    首先你需要模型来绑定你的数据。

     public class TestModel
        {
            public string Age { get; set; }
            public string Gender { get; set; } 
            ...
        }
    

    那么你需要将你的 dropLists 包装在表单标签中

    <form method='post'>
     @Html.DropDownList("Age")
    </form>
    

    以及接收已发布数据的操作

     [HttpPost]
            public ActionResult YourAction(TestModel model)//selected data here
            {
    
            }
    

    【讨论】:

      【解决方案4】:

      在@using (Html.BeginForm("NameOfActionMethod", "ControllerName", FormMethod.Post)) 中,您应该输入您的输入。

      你在表单之外有你的输入

       @using (Html.BeginForm("NameOfActionMethod", "ControllerName", FormMethod.Post))
      {
         <input type="submit" value="Find" />
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 2013-04-25
        • 2019-11-13
        相关资源
        最近更新 更多