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

ASP.NET Framework中如何用JavaScript实现多表关联多选功能?

解决方案:实现Category Create页面多选PriceList

一、修改Create视图(Create.cshtml)

原视图使用的是单选下拉框,需要替换为支持多选的控件,以下提供两种方案:

方案1:复选框组(直观的多选体验)

替换原PricelistId下拉框部分为以下代码:

<div class="form-group">
    @Html.Label("选择Stage", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @foreach (var item in ViewBag.PricelistId as List<SelectListItem>)
        {
            <div class="checkbox">
                <label>
                    <input type="checkbox" name="PricelistId" value="@item.Value" /> @item.Text
                </label>
            </div>
        }
        @Html.ValidationMessage("PricelistId", "", new { @class = "text-danger" })
    </div>
</div>

方案2:多选下拉框(适合选项较多的场景)

如果偏好下拉式多选,可使用HTML原生多选下拉:

<div class="form-group">
    @Html.Label("选择Stage", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.ListBox("PricelistId", ViewBag.PricelistId as List<SelectListItem>, new { @class = "form-control", size = 5 })
        <small class="text-muted">按住Ctrl键可多选</small>
        @Html.ValidationMessage("PricelistId", "", new { @class = "text-danger" })
    </div>
</div>

二、优化控制器Create GET方法

原代码中重复赋值ViewBag.PricelistId,可简化为:

public ActionResult Create()
{
    ViewBag.PricelistId = new SelectList(db.PriceLists, "PricelistId", "Stage");
    return View();
}

三、可选:添加全选/反选交互

如果需要全选功能,在@section Scripts中添加JavaScript:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        $("#selectAll").click(function() {
            $('input[name="PricelistId"]').prop('checked', $(this).prop('checked'));
        });
    </script>
}

然后在复选框组上方添加全选按钮:

<div class="col-md-10">
    <div class="checkbox">
        <label>
            <input type="checkbox" id="selectAll" /> 全选
        </label>
    </div>
    <!-- 原复选框循环代码 -->
</div>

四、Edit页面适配(可选)

如果需要在Edit页面回显已选中的选项,修改Edit GET方法:

public async Task<ActionResult> Edit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var category = await db.Categories.FindAsync(id);
    if (category == null)
    {
        return HttpNotFound();
    }

    // 解析已选中的ID数组
    int[] selectedIds = category.PricelistIdList.Split(',').Select(int.Parse).ToArray();
    // 生成带选中状态的选项列表
    ViewBag.PricelistId = new SelectList(db.PriceLists, "PricelistId", "Stage", selectedIds);

    // 原有视图数据传递逻辑...
    return View(category);
}

Edit视图同样使用上述复选框组或多选下拉框即可实现回显。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:29:52