ตัวอย่าง
จากไฟล์ Views/Movies/Index.cshtml เพิ่ม Code ด้านล่าง
@model IEnumerable<MvcMovie.Models.Movie> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create")@using (Html.BeginForm("Index", "Movies", FormMethod.Get)) { <p> Title: @Html.TextBox("SearchString") Genre: @Html.DropDownList("movieGenre", "All") <input type="submit" value="Filter" /> </p> }</p> <table class="table">
- รับค่า Title ด้วย Textbox
- รับค่า Genre ด้วย Dropdownlist
- ปุ่มจะกรองค่าตามที่ได้ระบุ และส่งผ่าน Action Html.BeginForm("Index", "Movies", FormMethod.Get) โดยที่ "Index" คือชื่อ ActionName "Movies" คือชื่อ Controller โดยส่งค่าจาก Form ทั้งหมด จาก Code ข้างต้นคือ SearchString และ movieGenre
จากไฟล์ MovieController.cs เพิ่ม Code ด้านล่าง
public ActionResult Index(string movieGenre, string searchString) {var GenreLst = new List<string>(); var GenreQry = from d in db.Movies orderby d.Genre select d.Genre; GenreLst.AddRange(GenreQry.Distinct()); ViewBag.movieGenre = new SelectList(GenreLst);var movies = from m in db.Movies select m;if (!String.IsNullOrEmpty(searchString)) { movies = movies.Where(s => s.Title.Contains(searchString)); }if (!string.IsNullOrEmpty(movieGenre)) { movies = movies.Where(x => x.Genre == movieGenre); }return View(movies); }
- รับ Parameter 2 ค่า movieGenre และ searchString เพื่อรับค่าจาก Action จากไฟล์ Views/Movies/Index.cshtml
- ประกาศตัวแปร GenreLst รับค่า GenreQry ที่ดึงข้อมูล d.Genre ทั้งหมดด้วย Linq จาก db.Movies
- Distinct ค่าที่ซ้ำกัน ทั้งนี้โยนค่าทั้งหมดที่กรองมาใส่ ViewBag.movieGenre เพื่อนำค่าดังกล่าวไปแสดงที่หน้า Views/Movies/Index.cshtml
- หากค่า Parameter ที่รับค่าเข้ามามีข้อมูล จะถูกกรองตามส่วนทีไ่ด้ค้นหา
เมื่อ Run Application จะได้ผลดังรูป

No comments:
Post a Comment