首页 > 解决方案 > 如何在剃刀编辑页面上仅检索位置/实体关系的过滤值

问题描述

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

我将以康宁医院为例。它有两个地点,自助餐厅和凉亭2。 在此处输入图像描述

当用户尝试编辑现有记录时,它确实选择了正确的位置项(凉亭 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>`);
                    });
                });
            });
        });

编辑.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();
} 

标签: c#ajaxasp.net-corerazor-pages

解决方案


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

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

推荐阅读