Search with Checkbox

Asked

Viewed 130 times

2

I am trying to create a search system in my application where the user can search the site publications according to gender. I can list the generos registered with checkbox, but I’m lost to do the search query from there.

I have the following tables:

Publicacao
Genero
PublicacaoGenero(IdPublicacao e IdGenero)

Edit:

public ActionResult Publicacoes(PesquisaPublicacoesViewModel viewModel = null)
        {
            if (viewModel == null)
            {
                PesquisaPublicacoesViewModel p = new PesquisaPublicacoesViewModel();
                p.TodosOsGeneros = db.Generos.ToList();
                p.PublicacoesSelecionadas = db.Publicacao.Where(x => x.Titulo.StartsWith(p.Titulo) && x.Aprovado).ToList();
                return View(p);

            }

            viewModel.TodosOsGeneros = db.Generos.ToList();


            if (string.IsNullOrEmpty(viewModel.Titulo))
            {
                viewModel.PublicacoesSelecionadas = db.Publicacao.Where(p => p.Aprovado).ToList();

            }
            else
            {
                viewModel.PublicacoesSelecionadas = db.Publicacao.Where(p => p.Titulo.StartsWith(viewModel.Titulo) && p.Aprovado).ToList();

            }

            return View(viewModel);
        }

View:

 @model AllFiction.ViewModels.PesquisaPublicacoesViewModel

@using(Html.BeginForm("Publicacoes","Publicacoes",FormMethod.Get))
{

@Html.TextBox("Titulo", null, new {id="txtTitulo" })


@Html.CheckBoxListFor(model => model.IdGenerosSelecionados,
                        model => model.TodosOsGeneros,
                        genero => genero.IdGenero,
                        genero => genero.Genero,
                        model => model.GenerosSelecionados)

}

@foreach (var p in Model.PublicacoesSelecionadas)
{
    @p.Usuario1.NomeCompleto
    @p.Titulo
}

I tried to add foreach so I could list the posts, which works. However, it ignores the options selected in the checkbox, and displays all posts (if the user does not type anything) or posts that have the characters typed in the text box.

1 answer

1


For this, you will need to use the Nuget package Mvccheckboxlist:

https://www.nuget.org/packages/MvcCheckBoxList/

Before mount a ViewModel with a few things:

public class PesquisaPublicacoesViewModel
{
    // Coloque aqui todos os parâmetros que você usa pra fazer a pesquisa
    public string Titulo { get; set; }

    public IEnumerable<Publicacao> PublicacoesSelecionadas { get; set; }

    public string[] IdsDosGenerosSelecionados { get; set; }
    public IList<Genero> TodosOsGeneros;
    public IList<Genero> GenerosSelecionados;
}

Then put it on your View:

@model SeuProjeto.ViewModels.PesquisaPublicacoesViewModel

@Html.CheckBoxListFor(model => model.IdsDosGenerosSelecionados,
                        model => model.TodosOsGeneros,
                        genero => genero.GeneroId,
                        genero => genero.Nome,
                        model => model.GenerosSelecionados)

Therefore, that Controller now get like this:

public ActionResult Publicacoes(PesquisaPublicacoesViewModel viewModel = null)
{
    if (viewModel == null) {
        // Inicie o ViewModel com alguns dados padrão.
    }

    viewModel.TodosOsGeneros = db.Generos.ToList();
    // Essa linha abaixo é facultativa. Coloque apenas se quiser que os gêneros já venham preenchidos.
    viewModel.GenerosSelecionados = db.Generos.Where(...);

    List<Publicacao> pub;

    if (string.IsNullOrEmpty(pesquisa))
    {
        viewModel.PublicacoesSelecionadas = db.Publicacao.Where(p => p.Aprovado).ToList();

    }
    else
    {
        viewModel.PublicacoesSelecionadas = db.Publicacao.Where(p => p.Titulo.StartsWith(viewModel.Titulo) && p.Aprovado).ToList();

    }

    return View(viewModel);
}
  • Just explain two things to me, please. I don’t quite understand the line "// Start Viewmodel with some standard data." Would instantiate the Search Publishing class viewmodel? And what exactly are Viewmodels?

  • 1

    Yes, it is necessary to instantiate the class if it is null in the request. Viewmodels sane Models that are not persisted in bank. They are perfect to assemble screens and put there the information you want.

  • 1

    Got it. Thanks for your help.

  • Take one more question, please. What should I add to the view in order to display the posts? I tried to use a foreach, but it did not work very well, it ends up displaying all publications independent of the chosen genre... If you need me I’ll open another question.

  • @Ryansantos Better open another one, so I can understand your code now.

  • I decided to edit because I didn’t make any major changes to the code. If you can take a look now.

  • I’m pretty sure it’s not correct... I don’t know if I can explain it properly. But I think I should do an if to be able to compare which generous user has checked and which publications fit these values...

  • @Ryansantos There are no comparisons with genders in his Where(). Ask another question that the explanation is a little long.

  • Here: http://answall.com/questions/40678/filtrar-searchcom-values-da-checkbox

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.