【问题标题】:Pass the dropdown selected value to the view in Html.BeginForm()将下拉选择的值传递给 Html.BeginForm() 中的视图
【发布时间】:2017-05-17 16:04:51
【问题描述】:

我需要将字段的值从视图传递到控制器。我的代码适用于文本框,但不适用于下拉菜单。我已经看到了很多 Html.DropdownlistFor 的答案,但对于这种情况却没有。有什么办法可以做到吗?

查看:

@var searchTypes = new SelectList(new[]
{
   new SelectListItem {Value = "0", Text = "Email"},
   new SelectListItem {Value = "1", Text = "Last Name"},
   new SelectListItem {Value = "2", Text = "First Name"},
}, "Value", "Text");

 @using (Html.BeginForm("Index", "Users", new { isSearch = 1, searchTerm = "SearchTerm", searchType="ddlSearchType" }, FormMethod.Post))
{
  <div class="well well-sm search">
      <div class="row">
      <div class="col-sm-6">
        <div class="form-group">
            @Html.TextBox("SearchTerm",(string)ViewBag.SearchTerm, new {name= "SearchTerm", @class = "form-control", placeholder = "Search Term" })

        </div>
    </div>

    <div class="col-sm-3">
        <div class="form-group">
            <div class="controls">
                @Html.DropDownList("ddlSearchType", searchTypes, new { id = "searchtypeselect", @class = "form-control" })

            </div>
        </div>
    </div>

    <div class="col-sm-2">
        <button class="btn btn-primary pull-right" type="submit"><i class="glyphicon glyphicon-search"></i>Search</button>
    </div>
</div>
</div>
}

控制器:

public ActionResult Index(int? isSearch,string searchTerm,string searchType)
{

}

This answer 解决了同样的问题,但视图中没有文本框。

为了澄清,搜索部分只是我观点的一部分。我在它下面有一个分页列表。所以我需要 IsSearch 字段来查看是否按下了搜索按钮,或者它是否是页面更改,它也将转到相同的操作方法。

【问题讨论】:

    标签: c# asp.net-mvc html.beginform


    【解决方案1】:

    答案就在您发布的链接中。您需要从 Html.BeginForm 中删除下拉列表参数,并在控制器和下拉名称中使用相同的字符串。

    @using (Html.BeginForm("Index", "Users", new { isSearch = 1, searchTerm = "SearchTerm"}, FormMethod.Post))
    
    
    public ActionResult Index(int? isSearch,string searchTerm,string ddlSearchType)
    {
    
    }
    

    【讨论】:

      【解决方案2】:

      要纠正值的问题,您需要向搜索列表控制器添加第四个参数,该参数应该是选定的值。

      @var searchTypes = new SelectList(new[]
      {
         new SelectListItem {Value = "0", Text = "Email"},
         new SelectListItem {Value = "1", Text = "Last Name"},
         new SelectListItem {Value = "2", Text = "First Name"},
      }, "Value", "Text", selectedValueHere);
      

      接下来,您应该更改 BeginForm 帮助程序并删除您在那里拥有的路由属性。您可能没有为这些定义路由,并且您希望值来自表单提交,而不是您在帮助程序中发送的硬编码字符串。您也可以删除该方法,因为它默认为 POST。

       @using (Html.BeginForm("Index", "Users",new { isSearch = 1 }))
      

      最后,您需要调整下拉菜单的名称,使其与 POST 操作中预期的名称正确匹配。

      @Html.DropDownList("SearchType", searchTypes, new { id = "searchtypeselect", @class = "form-control" })
      

      【讨论】:

      • 我仍然需要 IsSearch 参数,它不是任何控件的一部分。它可以帮助我查看是否单击了搜索按钮。所以不能像你的建议那样把所有参数都拿出来。
      • 为什么需要知道? POST 操作不会表明这一点吗?
      • 好的。调整了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2019-05-17
      • 2020-12-22
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多