如何在 Razor 编辑页面上仅检索 location/entity 关系的过滤值

How to retrieve only filtered values for location/entity relationship on razor edit page

我正在从 sql 数据库(实体和位置)中检索两个列表。当实体被 selected 时,这会将位置值过滤为仅属于 selected 实体的那些值。这在创建条目或更改实体时工作正常,新位置字段会正确填充。但是,当我去编辑现有记录时,正确的位置是 selected,但它还会显示所有实体的所有位置,而不仅仅是 selected 实体。我不希望用户不小心 select 属于不同实体的位置。

我以康宁医院为例。它有两个位置,自助餐厅和凉亭 2。

当用户尝试编辑现有记录时,它会 select 正确的位置项(凉亭 2),但它也包含所有其他实体的位置项。

这是我的剃须刀编辑页面

<div class="form-group">
    <label asp-for="SecurityLog.EntityID" class="control-label"></label>
    <select id="entity" asp-for="SecurityLog.EntityID" class="form-control" asp-items="ViewBag.EntityID">
        <option value="">--Select Entity--</option>
    </select>
    <span asp-validation-for="SecurityLog.EntityID" class="text-danger"></span>
</div>
<div class="form-group">
    <label asp-for="SecurityLog.LocationID" class="control-label"></label>
    <select id="location" asp-for="SecurityLog.LocationID" class="form-control" asp-items="ViewBag.LocationID">
        <option value="">--Select Location--</option>
    </select>
    <span asp-validation-for="SecurityLog.LocationID" class="text-danger"></span>
</div>

这里是可以在 onchange 事件中过滤位置的地方

$(function () {
            $("#entity").on("change", function() {
                var entity = $(this).val();         
                $("#location").empty();                  
                $("#location").append("<option value=''>--Select Location--</option>");
                $.getJSON(`?handler=Locations&entity=${entity}`, (data) => {
                    $.each(data, function (i, item) {
                        $("#location").append(`<option value="${item.value}">${item.text}</option>`);
                    });
                });
            });
        });

Edit.cshtml.cs

SelectList FilteredLocation;

public JsonResult OnGetLocations()
{

    FilteredLocation = new SelectList(_context.Location.Where(c => c.EntityID == entity).Where(c => c.Active == "Y").OrderBy(c => c.Name), "ID", "Name");
   
    return new JsonResult(FilteredLocation);

}




[BindProperty(SupportsGet = true)]
public int entity { get; set; }

[BindProperty(SupportsGet = true)]
public int location { get; set; }

public async Task<IActionResult> OnGetAsync(int? id)
{   
    SecurityLog = await _context.SecurityLog.FirstOrDefaultAsync(m => m.ID == id);
    
    //Generating data for select dropdowns
    ViewData["EntityID"] = new SelectList(_context.Entity.Where(a => a.Active == "Y"), "ID", "Name");
    ViewData["LocationID"] = new SelectList(_context.Location.Where(a => a.Active == "Y"), "ID", "Name");
   
    return Page();
} 

您需要在此处更改OnGet方法以显示与当前EntityId对应的位置:

ViewData["LocationID"] = new SelectList(locations.Where(a => a.Active == "Y" & a.EntityID==SecurityLog.EntityID), "ID", "Name");