This book store really needs a search function. One notable difference is whether to return a single value, e.g. one person matching a phone number, or multiple values, e.g. a list of books.
A little modification to the Home Controller and the Index View will get us an input field and an output field for displaying results. For now, this will involve a full postback, reloading the page. In the single result example, it will send the user to the detail page for that item. In the list example, it will refresh the index page with the result. In case there are no results, I’ll provide some feedback that nothing was found.
1 2 3 4 5 6 7 8 |
<label class="control-label">Search Author by ID</label> <span class="alert-danger">@ViewBag.Message</span> @using (Html.BeginForm()) { <input type="text" name="AuthorId" /> <input type="submit" /> } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class HomeController : Controller { private BookStoreDb db = new BookStoreDb(); public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(string AuthorId) { //single int intId = Int32.Parse(AuthorId); var result = db.Authors.Where(a => a.AuthorId == intId).Single(); if (result != null) { return RedirectToAction("Details", "Authors", new { id = result.AuthorId}); } ViewBag.Message = "I couldn't find " + AuthorId; return View(); } } |
Resulting redirect to /Authors/Details/1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
@model IEnumerable<BookStore.Models.Book> @{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>BookStore.NET</h1> </div> <label class="control-label">Search Books by Title</label> <span class="alert-danger">@ViewBag.Message</span> @using (Html.BeginForm()) { <input type="text" name="bookTitle" /> <input type="submit" /> } @if (Model != null) { <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Author.FirstName) </th> <th> @Html.DisplayNameFor(model => model.Title) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Author.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.Title) </td> <td> @Html.ActionLink("Details", "Details", new { id = item.BookId }) </td> </tr> } </table> } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class HomeController : Controller { private BookStoreDb db = new BookStoreDb(); public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(string bookTitle) { //mutiple var results = db.Books.Where(b => b.Title.Contains(bookTitle)); if (results.Count() > 0) { return View(results); } ViewBag.Message = "I couldn't find " + bookTitle; return View(); } } |
Users should be alerted in the event nothing is found, i.e. when results.Count == 0.