Save and send selected item id in dropdowlinst

11

I'm trying to do a search by filtering through a dropdowlist. In summary, I select a level of instruction in a list and clicking on 'Search' I want to return the list of people who have that level of education. My problem is in identifying the item selected in the dropdownlist. If I select anything the search does not return anything to me. But if I pass a value to the id like in the example below, clicking on Search I get as a return all people who have that level equal to the id informed. What do I need to do to get the id of the selected item?

My Controller

public class FormacaoController : Controller
{
    private DataContext db = new DataContext();

    public ActionResult Index()
    {
        ViewBag.NívelId = new SelectList(db.Escolaridades, "Id", "Nome");
        return View();
    }

    [HttpPost]
    public ActionResult Pesquisa(int id = 3) // 'setando' um valor, ao clicar em buscar, retorna as informaçãos. Se não passar um valor aqui para o id, a consulta não retorna nada.
    {
        var resultado = db.Cursos.Include(c => c.Perfil).Where(c => c.NívelId == id);
        ViewBag.Perfil = db.Perfis.AsEnumerable();
        ViewBag.NívelId = new SelectList(db.Escolaridades, "Id", "Nome");

        return View(resultado);
    }
    }

View Index

    <div> 
 @using (Html.BeginForm("Pesquisa", "Formacao", FormMethod.Post))
 {
     IEnumerable<MinhaBase.Models.Perfil> modelPerfil = (IEnumerable<MinhaBase.Models.Perfil>)ViewBag.Perfil;

     <div class="form-group">
         @Html.DropDownList("NívelId")

     </div> 

     <button type="submit" id="pesquisar" class="btn btn-primary btn-xs">Buscar</button>
 }

View Search

<div> 
 @using (Html.BeginForm("Pesquisa", "Formacao"))
 {
     IEnumerable<MinhaBase.Models.Perfil> modelPerfil = (IEnumerable<MinhaBase.Models.Perfil>)ViewBag.Perfil;
     <div class="form-group">
         @Html.DropDownList("NívelId")

     </div> 

     <button type="submit" id="pesquisar" class="btn btn-primary btn-xs">Buscar</button>
 }

   <table>

    @{
        if (Model != null)
        {
            foreach (var item in Model)
            {
        <tr>
        <th>Nome <b>&nbsp; &nbsp; &nbsp;</b></th>


    </tr>
                <tr>
                   <td width="30%">@item.Nome></td> 
                    <td width="30%">@item.Instituição</td> 
                    <td width="30%">@item.Perfil.Nome</td> 
                </tr>
                }
            }
        }
</table>
    
asked by anonymous 09.12.2015 / 19:48

2 answers

7

Gypsy's Method of Implementing a Research Form

This is the method I use in my applications, and it has several advantages:

  • URL search parameters. It does not take a form to repeat the search. A simple F5 or [Ctrl / Command] + R already does this;
  • Friendly to SEO;
  • Search parameters are populated in the search form;
  • Search form can appear on any screen.

1. The search form must have FormMethod.GET

If it is a search, the parameters must be at the request address, so you can easily call the search without a form.

To do this, make Partial with the following:

_Pesquisa.cshtml

 @using (Html.BeginForm("Pesquisa", "Formacao", FormMethod.GET))
 {
     IEnumerable<MinhaBase.Models.Perfil> modelPerfil = (IEnumerable<MinhaBase.Models.Perfil>)ViewBag.Perfil;

     <div class="form-group">
         @Html.DropDownList("NivelId")
     </div> 

     <button type="submit" id="pesquisar" class="btn btn-primary btn-xs">Buscar</button>
 }

2. The search form should be a Partial

This is because it will possibly appear in N Views of your code.

3. Create a ViewModel that contains the search parameters and the result of it

That is:

public class PesquisaViewModel
{
    public int NivelId { get; set; }

    public virtual IEnumerable<Curso> Cursos { get; set; }
}

4. Controller should accept ViewModel in search

It can accept POST as well, but in my view it does not have to.

[HttpGet]
public ActionResult Pesquisa(PesquisaViewModel viewModel)
{
    if (viewModel != null) 
    {
        viewModel.Cursos = db.Cursos.Include(c => c.Perfil).Where(c => c.NivelId == viewModel.NivelId);
    }

    ViewBag.Perfil = db.Perfis;
    ViewBag.Niveis = db.Escolaridades;

    return View(viewModel);
}

5. _Pesquisa and the View search result should be typed by ViewModel

_Pesquisa.cshtml

 @model MeuProjeto.ViewModels.PesquisaViewModel

 @using (Html.BeginForm("Pesquisa", "Formacao", FormMethod.GET))
 {
     <div class="form-group">
         @Html.DropDownListFor(model => model.NivelId, ((IEnumerable<Escolaridade>)ViewBag.Niveis).Select(option => new SelectListItem 
         {
             Text = option.Nome,
             Value = option.NivelId.ToString(),
             Selected = (Model != null) && (Model.NivelId == option.NivelId)
         }), "Selecione...")
     </div> 

     <button type="submit" id="pesquisar" class="btn btn-primary btn-xs">Buscar</button>
 }

Pesquisa.cshtml

If the name is ambiguous, use ResultadoPesquisa.cshtml .

 @model MeuProjeto.ViewModels.PesquisaViewModel

 ...

6. Screens that do not use this ViewModel can call Partial without problems

So:

@Html.Partial("_Pesquisa", new PesquisaViewModel())
    
09.12.2015 / 20:05
2
  

I do not advise you to use this form that I will show, the Cigano's answer expresses a better way to search . I am posting just for the purpose of knowledge.

As the @CiganoMorrisonMendez explained, there is no need to use POST for a search, you lose the "reuse" or even disadvantage in Search Engine Optimization ( SEO ) .

Now, by answering your question, you could use jQuery or javascript to get the selected item and redirect to the page you want. An example would look like this:

   $('#pesquisar').click(function () {
            var nivel = $('#NivelId').find(":selected").val();
            location.href = '@Url.Action("Pesquisa","Formacao")?id=' + nivel;
        });

This way you will get the selected value and send it to your Action . Remember that if you want to use the filter only by changing the value of DropDownList , just use .change () instead of .click() .

    
09.12.2015 / 20:47