Search code examples
c#asp.net-mvchtml.beginform

Pass the dropdown selected value to the view in Html.BeginForm()


I need to pass the values of the fields from the view to the controller. My code works for the textbox but does not work for the dropdown. I have seen many answers for Html.DropdownlistFor but none for this case. Is there a way I can do this?

View :

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

Controller:

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

}

This answer tackles the same issue but it does not have a text box in the view.

To clarify, the search portion is only a part of my view. I have a paged list below it. So I need the IsSearch field to see if the search button is pressed or if it is a change of page which will also go to the same action method.


Solution

  • The answer is literally there in the link that you have posted. You need to remove the dropdown list parameter from the Html.BeginForm and use the same string in controller and in the dropdown name.

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