c# – Retrieve data with Request.QueryString

Question:

I have a Partial that loads the data:

@using (Html.BeginForm("PesquisarEventoPorLocal", "CadastroEvento", FormMethod.Get))
{
    <div class="row">
        <div class="col-sm-12 col-md-12">
            <div class="form-group col-md-3">
                <label for="sel2">Pesquisar Por local:</label>
                @Html.DropDownList("Pesquisa:", ViewBag.TiposLocal as SelectList, new { @class = "form-control", id = "comboBox", name= "comboBox" })
            </div>
            <div class="form-group  col-sm-3 col-md-3">
                <br/>
                <button type="submit" class="btn btn-danger">Pesquisar</button>
            </div>
        </div>
    </div>


}

The controller is not passing the data.

        [HttpGet]
        public ActionResult PesquisarEventoPorLocal()
        {
            string CodigoLocal = Request.QueryString["PesquisarEventoPorLocal"];
            string CodigoLocal1 = Request.QueryString["Pesquisa"];
            string CodigoLocal2 = Request.QueryString["comboBox"];

            return RedirectToAction("index", "CadastroEvento");
        }

Answer:

There are some errors in your code.

These fields below do not exist in your form, for them to exist you must create an input or select and add the name attribute and define a name for the element.

SearchEventByLocation

Search

comboBox

Note: The code below does not work the way you are expecting

@Html.DropDownList("Pesquisa:", ViewBag.TiposLocal as SelectList, new { @class = "form-control", id = "comboBox", name= "comboBox" })

Mainly these two attributes:

id = "comboBox", name= "comboBox"

When you create an @Html.DropDownList the first parameter is the id and name of the element, I haven't seen how you force the element to change the id and name passed this data by the htmlAttribute parameter. That's why when you submit the form you can't get the query Request.QueryString["comboBox"];


string CodigoLocal2 = Request.QueryString["comboBox"];

This code will be correct if you do it this way:

<div class="form-group col-md-3">
    <label for="sel2">Pesquisar Por local:</label>
    @Html.DropDownList("comboBox", ViewBag.TiposLocal as SelectList,"Pesquisa:", new { @class = "form-control" })
</div>
Scroll to Top