Search the Mysql MVC database

Asked

Viewed 136 times

2

I have a Search which searches by name, but wanted it to search both by name and by place in the same research 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 that var clientes wanted to search beyond the name, search the city, and bring everyone from that city, I believe it is in the where, but I don’t 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>
}

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());
}

Only add one operator || (AB) in the clause Where

Inverti your if to make the code more readable. And you don’t need ELSE because if already has a Return =D

  • Thanks Cara, it was for a project of the College and has already been finalized, but it will be of great use to me in the future, and when testing, mark the answer as accepted. Thank you

Browser other questions tagged

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