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

MVC C#同一视图中基于下拉选择将列表转为表格的实现问题

问题分析与解决方案

当前代码存在以下核心问题:

  • Controller直接返回实体列表,前端拿到的是JSON字符串而非可渲染的HTML
  • 主视图中表格的循环结构错误,导致HTML标签嵌套混乱
  • JS中对下拉框默认选项的判断逻辑错误
  • 初始状态下表格容器未隐藏,影响页面体验

方案1:使用PartialView渲染表格(推荐,符合MVC最佳实践)

1. 修改Controller方法,返回PartialView

将原方法改为返回局部视图,让MVC负责渲染表格HTML:

public ActionResult GetResult(int Id)
{
    var results = entities.tblResults.Where(a => a.result_id == Id).ToList();
    return PartialView("_ResultsTable", results);
}

2. 创建局部视图_ResultsTable.cshtml

在Views/Home目录下新建该视图,专门负责表格渲染:

@model List<tblResults>

<table class="table table-striped" style="width:85%" align="center">
    <thead>
        <tr>
            <th>结果ID</th>
            <th>名称</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@Html.DisplayFor(modelItem => item.result_id)</td>
                <td>@Html.DisplayFor(modelItem => item.name)</td>
            </tr>
        }
    </tbody>
</table>

3. 修正主视图代码

调整主视图的下拉框和表格容器,初始隐藏表格区域:

@if (ViewBag.Result != null)
{
    @Html.DropDownListFor(m => m.maindropdown, 
                          new SelectList(ViewBag.ResultGroup, "id", "mainvalues"), 
                          "请选择", 
                          new { @class = "form-control", @id = "dropdown" })
}

<div id="showorhide" style="display:none;">
    <!-- AJAX加载的表格将插入此处 -->
</div>

4. 修正JS逻辑

修复选中值判断,正确处理AJAX返回的HTML:

$("#dropdown").change(function () {
    var selectedValue = $(this).val();
    if (!selectedValue) {
        $("#showorhide").hide();
    } else {
        $.get('@Url.Action("GetResult", "Home")', { id: selectedValue }, function (result) {
            $("#showorhide").html(result).show();
        });
    }
});

方案2:返回JSON,前端动态生成表格

如果不想使用PartialView,可通过JSON返回数据,前端手动构建表格:

1. 修改Controller返回JsonResult

public JsonResult GetResult(int Id)
{
    var results = entities.tblResults.Where(a => a.result_id == Id).ToList();
    return Json(results, JsonRequestBehavior.AllowGet);
}

2. 修正JS逻辑

$("#dropdown").change(function () {
    var selectedValue = $(this).val();
    if (!selectedValue) {
        $("#showorhide").hide();
        return;
    }

    $.get('@Url.Action("GetResult", "Home")', { id: selectedValue }, function (results) {
        if (results.length === 0) {
            $("#showorhide").html("<p>未找到匹配结果</p>").show();
            return;
        }

        // 动态构建表格HTML
        var tableHtml = '<table class="table table-striped" style="width:85%" align="center">' +
                        '<thead><tr><th>结果ID</th><th>名称</th></tr></thead>' +
                        '<tbody>';
        
        $.each(results, function(index, item) {
            tableHtml += `<tr><td>${item.result_id}</td><td>${item.name}</td></tr>`;
        });

        tableHtml += '</tbody></table>';
        $("#showorhide").html(tableHtml).show();
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:06:27