You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC框架中选择下拉列表项时如何从数据库获取对应数据?

Fixing Category-Based Item Filtering in 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&nbsp; 
 <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 divView on page load, so your initial items appear in the container that gets updated later.
  • Polished JS: Removed unnecessary parameters, simplified Url.Action syntax, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:52:42