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

ASP.NET MVC 下拉框切换分类后无法加载对应图书问题求助

故障原因

你的问题核心有两个:

  1. 下拉框绑定了onchange = "SelectedIndexChanged()"触发事件,但没有定义对应的JavaScript函数,浏览器找不到该函数就会抛出未定义报错,这就是你截图里报错的直接原因。
  2. POST版本的Index接口逻辑存在缺失,表单提交后会出现下拉框空白、权限校验遗漏的问题。
修复步骤

1. 视图层补全JS代码和图书渲染逻辑

在你的Index视图末尾追加JS函数,同时替换原有的图书占位div:

@using (Html.BeginForm("Index", "BorrowBook", FormMethod.Post, new { name = "demoForm" }))
{
    @Html.DropDownList("id_category", (IEnumerable<SelectListItem>)ViewBag.listTest, "-- Select Category --",
         new { onchange = "SelectedIndexChanged()" })
    <div>
        @* 渲染分类下的图书列表,字段名替换为你Book实体的实际字段 *@
        @if (ViewBag.list != null)
        {
            <ul>
                @foreach (var book in ViewBag.list)
                {
                    <li>@book.书名字段 @book.作者字段</li>
                }
            </ul>
        }
    </div>
}

<script>
// 下拉框切换时触发表单提交
function SelectedIndexChanged() {
    document.demoForm.submit();
}
</script>

2. 修正控制器POST方法逻辑

修改后的POST方法需要补全权限校验、下拉框数据源重新绑定、选中状态保留的逻辑:

[HttpPost]
public ActionResult Index (int id_category)
{
    // 补全权限校验,避免未授权访问
    var userInfomatiom = (LibraryAsp.Models.User)Session["USER"];
    if (userInfomatiom?.Role.id_role != 1)
    {
        return RedirectToAction("Error", "Home");
    }
    // 重新绑定下拉框数据源,第四个参数用于保持用户选中的分类状态
    var query = context.categories.Select(c => new { c.id_category, c.name });
    ViewBag.listTest = new SelectList(query.AsEnumerable(), "id_category", "name", id_category);
    
    ViewBag.listP = publisherDao.getAll();
    ViewBag.listC = categoryDao.getAll();
    ViewBag.list = context.books.Where(p => p.id_category == id_category).ToList();
    return View();
}

这里直接用int id_category作为接口参数,比绑定整个Category实体更简洁,MVC会自动匹配表单提交的id_category字段完成参数赋值。

内容的提问来源于stack exchange,提问作者Mohtep

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:54:04