MVC框架中选择下拉列表项时如何从数据库获取对应数据?
Hey there! Let's get your category dropdown filtering working smoothly. You've got the core idea down, but a few tweaks will make this functional and clean. Here's what to adjust:
1. Split Your View into a Partial for Item List
Right now, your controller returns the full Index view when the dropdown changes—this means you'll end up repeating the page header and dropdown inside your divView container. Instead, move the item display logic into a partial view so only the item list gets refreshed.
Create _ItemList.cshtml Partial View
@model IEnumerable<YourProjectName.Models.Items> @foreach (var item in Model) { <div class="col-md-2"> <img class="img-responsive img-rounded" src="/Item/RetrieveImage/@item.Id" /> <div> <p>@item.ItemName</p> <p>Rs.<span>@item.Price</span><span class="pull-right">Order <input type="checkbox" name="cbOrder" id="@item.Id" /></span></p> </div> </div> }
2. Update the Controller Action
Modify your Index action to return the partial view for AJAX requests, and the full view for the initial page load:
public ActionResult Index(int id = 1) { var items = db.Items.Where(i => i.CategoryID == id).ToList(); var categories = db.Categories.ToList(); ViewBag.Categories = categories; // Return partial view for AJAX calls, full view otherwise if (Request.IsAjaxRequest()) { return PartialView("_ItemList", items); } return View(items); }
3. Adjust the Main Index View
Update your main view to load the partial view inside divView (so initial items show up in the right place), clean up the dropdown JS, and remove the unnecessary submit button:
<h2>Index</h2> <div class="form-group"> <div class="col-md-10"> @Html.DropDownList("Categories", new SelectList(ViewBag.Categories, "CategoryID", "CategoryName"), "--Please Select--", htmlAttributes: new { @class = "form-control" }) </div> </div> <div id="divView"> <!-- Load initial items using the partial view --> @Html.Partial("_ItemList", Model) </div> <script> $("#Categories").change(function () { var selectedCategoryId = $(this).val(); $.ajax({ url: '@Url.Action("Index","Item")', data: { id: selectedCategoryId }, type: "GET", dataType: "html", beforeSend: function() { // Optional: Add loading state for better UX $("#divView").html("<p>Loading items...</p>"); }, success: function (data) { $("#divView").html(data); }, error: function() { $("#divView").html("<p>Oops! Failed to load items.</p>"); } }); }); </script>
Key Fixes Explained:
- Partial View: Separates the item display logic so AJAX only refreshes what's necessary (no duplicate page headers or dropdowns).
- AJAX Detection:
Request.IsAjaxRequest()tells the controller to return just the item list instead of the full page. - Initial Placement: The partial view loads inside
divViewon page load, so your initial items appear in the container that gets updated later. - Polished JS: Removed unnecessary parameters, simplified
Url.Actionsyntax, and added optional loading/error states to improve user experience.
That should get your dropdown filtering working exactly as you want—select a category, and the item list updates instantly without a full page refresh!
内容的提问来源于stack exchange,提问作者Waqas Qureshi

