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

ASP.NET Razor Pages多选下拉框绑定多值并存储ChargeCode逗号列表

解决方案步骤

1. 调整后端PageModel属性

在你的PageModel中新增一个用于接收多选选中项ID的集合属性,同时保留Incident实体的ArrestCharges字符串字段:

public class IncidentCreateModel : PageModel
{
    private readonly AppDbContext _context;

    public IncidentCreateModel(AppDbContext context)
    {
        _context = context;
    }

    // 绑定多选下拉框选中的Charge ID集合
    [BindProperty]
    public List<int> SelectedChargeIds { get; set; }

    // 要保存的Incident实体
    [BindProperty]
    public Incident Incident { get; set; }

    // 下拉框选项集合
    public IEnumerable<SelectListItem> ChargeOptions { get; set; }

    public async Task OnGetAsync()
    {
        // 从数据库加载所有Charge并转换为下拉框选项
        var charges = await _context.Charges.ToListAsync();
        ChargeOptions = charges.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = $"{c.ChargeCode} - {c.ChargeDesc}" // 可按需调整显示文本
        });
    }
}

2. 修改前端多选下拉框代码

确保<select>标签开启多选模式,并绑定到新增的SelectedChargeIds属性:

<div class="form-group">
    <label asp-for="SelectedChargeIds" class="control-label">逮捕罪名</label>
    <select asp-for="SelectedChargeIds" asp-items="Model.ChargeOptions" multiple class="form-control"></select>
    <span asp-validation-for="SelectedChargeIds" class="text-danger"></span>
</div>

3. 调整保存逻辑(OnPost方法)

在提交保存时,根据选中的ID查询对应Charge记录,提取ChargeCode并拼接成逗号分隔的字符串,赋值给Incident的ArrestCharges字段:

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        // 验证失败时重新加载下拉框选项
        var charges = await _context.Charges.ToListAsync();
        ChargeOptions = charges.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = $"{c.ChargeCode} - {c.ChargeDesc}"
        });
        return Page();
    }

    // 查询选中的Charge记录
    var selectedCharges = await _context.Charges
        .Where(c => SelectedChargeIds.Contains(c.Id))
        .ToListAsync();

    // 拼接ChargeCode为逗号分隔的字符串
    Incident.ArrestCharges = string.Join(", ", selectedCharges.Select(c => c.ChargeCode));

    // 保存到数据库
    _context.Incidents.Add(Incident);
    await _context.SaveChangesAsync();

    return RedirectToPage("./Index");
}

额外注意事项

  • 确保Incident实体的ArrestCharges字段为string类型,可通过EF Core的[MaxLength]特性设置足够长度。
  • 若为编辑页面,需要回显已选中的选项,可在OnGetAsync中从已保存的ArrestCharges反推选中ID:
// 编辑场景下的回显逻辑
var chargeCodes = Incident.ArrestCharges.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
SelectedChargeIds = await _context.Charges
    .Where(c => chargeCodes.Contains(c.ChargeCode))
    .Select(c => c.Id)
    .ToListAsync();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:15:34