What I did in a system of my own was to create a Controller common implementation of the research method. Something like this:
public abstract class Controller<TSource> : System.Web.Mvc.Controller
where TSource: class, IPesquisavel, new()
{
protected MeuContext db = new MeuContext();
public ActionResult Pesquisar(String termo)
{
var lista = db.Set<TSource>().Where(s => s.TermoPesquisa.Contains(termo)).ToList();
return View(lista);
}
}
To View you can put in Views/Shared (a little more complex to implement), or else make a View Pesquisar.cshtml for each Controller that has this research.
Implement IPesquisavel thus:
public interface IPesquisavel
{
String TermoPesquisa { get; }
}
The Model that can receive this research gets like this:
public class MeuModel
{
...
public String Nome { get; set; }
public String Descricao { get; set; }
[DisplayName("Termo de Pesquisa")]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public String TermoPesquisa
{
// No get, coloque os campos que interessam pra pesquisa, separados
// por vírgula. Por exemplo, Nome e Descricao
get { return Nome + ", " + Descricao; }
private set { }
}
}
By generating the Migration, Entity Framework does not understand that it is a calculated field. Comment on its generation and write in hand:
public partial class TestePesquisavel : DbMigration
{
public override void Up()
{
// AddColumn("dbo.MeuModels", "TermoPesquisa", c => c.String());
Sql("ALTER TABLE dbo.MeuModels ADD TermoPesquisa AS Nome + ', ' + Descricao");
}
public override void Down()
{
// DropColumn("dbo.MeuModels", "TermoPesquisa");
Sql("ALTER TABLE dbo.MeuModels drop column TermoPesquisa");
}
}
in my case, I have a View already on
Sharedcalled _Layout, where here is the system menu, and the search wanted to put it here too. In this case, a Controller would already solve?– Mario Puebla Junior
You can do it. It’s going to get a little more complicated because you’re going to have to use
Reflectionto read the properties and write it right, but it works.– Leonel Sanches da Silva
Suggest some other method for a layman and little experience?
– Mario Puebla Junior
This is the simplest method I know, which is to implement a Action common to all Controllers. The rest depart from unnecessary eccentricities.
– Leonel Sanches da Silva
Good morning @Gypsy, could you ask me one more question please? I am adapting the code to my system, what would be the "Meucontext"?
– Mario Puebla Junior
@Mariopueblajunior would be your data context. I’m guessing you’re using the Entity Framework.
– Leonel Sanches da Silva