Search code examples
asp.net-mvcentity-frameworkcode-first

Querying database with Entity Framework and displaying the results in a view


I got the following issue. I'm trying do query my database which was created with code first approach and display the query results in my view.

This is my model class :

public class AddApartmentViewModel
{
    public string City { get; set; }
}

public class SearchViewModel
{
    public string Query { get; set; }
}

This is my search controller

public class SearchController : Controller
{
    private ApartmentContext db = new ApartmentContext();

    [HttpPost]
    public ActionResult Search(SearchViewModel model)
    {
        var results = db.Apartments.ToList();
        return View(results);
    }
}

and this is my search bar which I'm trying to use as a partial view

@using (Html.BeginForm("Search", "SearchController"))
{ 
    @Html.TextBox("Query")
    <input type="submit" value="Search">
}

The whole idea is to display search results like in this example

http://www.zoopla.co.uk/to-rent/property/aberdeen/

How to manage this?


Solution

  • I strongly recommend reading this if You want to get listView with search functionality using entity framework.

    http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application