With the models and repository coded, the next step is to create the controller. Right click on the “Controllers” directory in the project and select Add -> Controller. Name the controller “BreweriesController” and select the template “Controller with empty read/write actions,” which will create actions for creating, updating, deleting, showing and listing breweries.
The Index method of the BreweriesController
will be used to display the list of breweries. To allow the new
controller to access brewery data, it will need an instance of a
BreweryRepository. Create a public property of
type BreweryRepository and instantiate it in
the default constructor.
public BreweryRepository BreweryRepository { get; set; } public BreweriesController() { BreweryRepository = new BreweryRepository(); }
Then inside of the Index method, add a call to
BreweryRepository's GetAll
method and pass its results to the view as its model.
public ActionResult Index() { var breweries = BreweryRepository.GetAll(); return View(breweries); }
The last step to displaying the list of breweries is to create the
Razor view (as in MVC views, not Couchbase views). In the
“Views” directory, create a new directory named
“Breweries.” Right click on that new directory and select
“Add” -> “View.” Name the view “Index” and create it
as a strongly typed (to the Brewery class) view
with List scaffolding. This template will create a Razor view that
loops over the brewery results, displaying each as a row in an
HTML table.
At this point, you should build your application and navigate to the Breweries path (e.g., http://localhost:52962/breweries). If all went well, you should see a list of breweries.
There are quite a few breweries being displayed in this list. Paging will be an eventual improvement, but for now limiting the results by modifying the defaults of the GetAll method will be sufficient.
//in RepositoryBase public IEnumerable<T> GetAll(int limit = 0) { var view = _Client.GetView<T>(_designDoc, "all", true); if (limit > 0) view.Limit(limit); return view; } //in BreweriesController public ActionResult Index() { var breweries = BreweryRepository.GetAll(50); return View(breweries); }
For more information about using views for indexing and querying from Couchbase Server, here are some useful resources:
For technical details on views, how they operate, and how to write effective map/reduce queries, see Couchbase Server 2.0: Views and Couchbase Sever 2.0: Writing Views.
Sample Patterns: to see examples and patterns you can use for views, see Couchbase Views, Sample Patterns.
Timestamp Pattern: many developers frequently ask about extracting information based on date or time. To find out more, see Couchbase Views, Sample Patterns.