Search in MySQL database MVC

2

I have Search searching by name, but wanted to search for both name and place in the same search field.

Follow the action:

[HttpPost]
        public ActionResult Search(FormCollection fc, string searchString)
        {
            if (!String.IsNullOrEmpty(searchString))
            {
                var clientes = db.Locals.Include(c => c.Cidades).Include(e => e.Cidades.Estado).Where(c => c.Nome.Contains(searchString)).OrderBy(o => o.Nome);
                return View("Index", clientes.ToList());
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

In this var clientes wanted to search beyond the name, search the city, and bring all of that city, I believe it is in where itself, but I do not know ...

This is the search HTML:

@*Código de pesquisa*@
using (Html.BeginForm("Search", "Local", null, FormMethod.Post))
{
   @Html.AntiForgeryToken()
   <div class="form-horizontal">
      @Html.ValidationSummary(true, "", new { @class = "text-danger" })
      <div class="form-group">
         <div class="col-md-10">
         @* @Html.TextBox("SearchString")*@
         Pesquisar: <input type="text" name="SearchString" id="SearchString" class="form-control" value="@ViewBag.Pesquisa" />
        <input type="submit" value="Pesquisar" class="btn btn-default" />
        </div>
     </div>
  </div>
}
    
asked by anonymous 08.10.2016 / 19:57

1 answer

1
[HttpPost]
public ActionResult Search(FormCollection fc, string searchString)
{
    if (String.IsNullOrEmpty(searchString))
        return RedirectToAction("Index");
    var clientes = db.Locals
               // Não precisa do include na Cidades, porque quando você inclui o Estado que está dentro da Cidades ele já traz Cidades!
               //.Include(l => l.Cidades)
               .Include(l => l.Cidades.Estado)
               .Where(l => 
                      l.Nome.Contains(searchString) ||
                      l.Cidades.Nome.Contains(searchString)) //Não sei o nome do campo, só um exemplo...
               .OrderBy(l => l.Nome);
    return View("Index", clientes.ToList());
}

Just add a || (OR) operator in the where clause

Inverted your if to make the code more readable. And you do not need ELSE because in if it already has a return = D

    
14.01.2017 / 21:14