Screen Search Field (ASP.Net - MVC)

2

Good afternoon,

I wonder if anyone could help me. I'm a beginner in programming, and I'm developing a web system, and I need a screen search of the screens that I've already created.

As I use the MVC method, I wanted to know if I have to create a View / Controller with the name Search.

** Remembering that I want to leave this on the home screen, and when I search, I wanted it to explode a box with the results, similar to the process that the site ( link ) performs.

Thanks for reading this far!

I use VS2013, and the database uses SQL Server.

    
asked by anonymous 02.07.2015 / 21:38

1 answer

2

What I did on my system was to create a common Controller that implements the search 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);
    }
}

View you can put in Views/Shared (a little more complex to implement), or make a View Pesquisar.cshtml for each Controller who has this search.

Implement IPesquisavel like this:

public interface IPesquisavel
{
    String TermoPesquisa { get; }
}

The Model that can receive this search looks 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 { }
    }
}

When generating Migration , the Entity Framework does not understand that it is a calculated field. Comment on his 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");
    }
}
    
02.07.2015 / 21:45