I'm trying to create a search system in my application where the user can search the site's publications according to the genre. I can list the registered genres 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 to be able to 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.