List groups are flexible components that either display simple lists of elements or can be combined with other elements to create complex lists with custom content. As an example, we'll create a sample search page that will display the search results in a Bootstrap list group.
Start by completing the following steps:
SearchController.cs
to your project.Index
action to the following:public IActionResult Index(string query) { ViewBag.SearchQuery = query; var products = GetProducts(); if (!string.IsNullOrEmpty(query)) { var results = products.Where(p => p.Name.Contains(query)); return View(results); } return View(products); }
GetProducts
method. It will then filter the list of products if the query
parameter contains a value and returns the results. If the query parameter does not contain any value, it will return all the products.GetProducts
method is as follows:private List<ProductModel> GetProducts() { var model = new List<ProductModel>(); var product1 = new ProductModel { Name = "Chai", UnitPrice = 18, UnitsInStock = 35, Discontinued = false, Id = 1, Status = "active" }; var product2 = new ProductModel { Name = "Chang", UnitPrice = 19, UnitsInStock = 17, Discontinued = false, Id = 2, Status = "success" }; var product3 = new ProductModel { Name = "Aniseed Syrup", UnitPrice = 10, UnitsInStock = 13, Discontinued = false, Id = 3, Status = "info" }; var product4 = new ProductModel { Name = "Pavlova", UnitPrice = 17, UnitsInStock = 29, Discontinued = false, Id = 4, Status = "warning" }; var product5 = new ProductModel { Name = "Carnarvon Tigers", UnitPrice = 62, UnitsInStock = 42, Discontinued = true, Id = 5, Status = "danger" }; model.AddRange(new[] { product1, product2, product3, product4, product5 }); return model; }
Views
folder called Search
and add a new view called Index.cshtml
to it.@model IEnumerable<Chapter3.Models.ProductModel> <div class="container" style="padding-top: 30px;"> <h1> Product search results <small> @if (ViewBag.SearchQuery != null) {<text>Results for your search term: </text> @ViewBag.SearchQuery } </small> </h1> <ul class="list-group"> @foreach (var item in Model) { <li class="list-group-item"> <span class="label label-default label-pill pull-xs-right"> @item.UnitsInStock</span> @item.Name </li> } </ul> </div>
<ul>
as anchor <li>
elements. Each <li>
element's class name should be set to .list-group-item
. The view should look like the following screenshot inside your browser:3.138.37.151