如何在Razor编辑页面中仅获取实体-位置关联的过滤后选项值
问题根因
编辑页首次加载时直接绑定了全量位置数据,你写的实体下拉change事件仅在手动切换实体时触发,首次加载不会自动执行过滤逻辑,因此会展示所有实体的位置选项。
修复步骤
1. 修改后端Edit.cshtml.cs的OnGetAsync方法
编辑页首次加载时就返回当前实体对应的过滤后位置列表,避免用户先看到全量位置再闪变为过滤结果:
public async Task<IActionResult> OnGetAsync(int? id) { SecurityLog = await _context.SecurityLog.FirstOrDefaultAsync(m => m.ID == id); // 实体下拉保留全量激活数据 ViewData["EntityID"] = new SelectList(_context.Entity.Where(a => a.Active == "Y"), "ID", "Name"); // 位置下拉根据当前编辑记录的实体ID过滤 if (SecurityLog?.EntityID > 0) { ViewData["LocationID"] = new SelectList(_context.Location .Where(a => a.Active == "Y" && a.EntityID == SecurityLog.EntityID) .OrderBy(a => a.Name), "ID", "Name"); } else { // 新增场景默认给空位置选项,也可按需调整 ViewData["LocationID"] = new SelectList(Enumerable.Empty<SelectListItem>(), "ID", "Name"); } return Page(); }
2. 优化前端JS逻辑
新增页面加载完成后的自动触发逻辑,同时保留切换实体时的过滤能力,且自动选中当前编辑记录的位置:
$(function () { // 封装位置加载公共方法 function loadLocations(entityId, selectedLocationId) { $("#location").empty(); $("#location").append("<option value=''>--Select Location--</option>"); $.getJSON(`?handler=Locations&entity=${entityId}`, (data) => { $.each(data, function (i, item) { let selectedAttr = item.value == selectedLocationId ? "selected" : ""; $("#location").append(`<option value="${item.value}" ${selectedAttr}>${item.text}</option>`); }); }); } // 实体切换时的过滤逻辑 $("#entity").on("change", function() { const currentEntity = $(this).val(); loadLocations(currentEntity, ""); }); // 页面首次加载自动触发过滤,保留已选位置 const initEntity = $("#entity").val(); const initLocation = $("#location").val(); if (initEntity) { loadLocations(initEntity, initLocation); } });
3. 优化后端接口校验(可选)
给OnGetLocations方法加参数校验,避免非法参数报错:
public JsonResult OnGetLocations(int entity) { if (entity <= 0) { return new JsonResult(Enumerable.Empty<SelectListItem>()); } var FilteredLocation = new SelectList(_context.Location .Where(c => c.EntityID == entity && c.Active == "Y") .OrderBy(c => c.Name), "ID", "Name"); return new JsonResult(FilteredLocation); }
内容的提问来源于stack exchange,提问作者Rob C
相关产品推荐
相关产品推荐

