c# - 如何在剃刀编辑页面上仅检索位置/实体关系的过滤值
问题描述
我正在从 sql 数据库(实体和位置)中检索两个列表。选择实体时,这会将位置值过滤为仅属于所选实体的那些值。这在创建条目或更改实体时工作正常,新的位置字段会正确填充。但是,当我去编辑现有记录时,会选择正确的位置,但它还会显示所有实体的所有位置,而不仅仅是所选实体的位置。我不希望用户意外选择属于不同实体的位置。
当用户尝试编辑现有记录时,它确实选择了正确的位置项(凉亭 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();
}
解决方案
您需要OnGet
在此处更改方法以显示具有当前 EntityId 的相应位置:
ViewData["LocationID"] = new SelectList(locations.Where(a => a.Active == "Y" & a.EntityID==SecurityLog.EntityID), "ID", "Name");
推荐阅读
- c# - C# 为什么我的运算符重载会改变对象而不是返回一个新对象?
- php - PHP - 在流中转换字节数组
- detox - Detox :: Timeout - 在 jest.setTimeout 指定的 120000 毫秒超时内未调用异步回调
- java - Spring Integration 新文件回调?
- sql - 在 VIEW 中使用 IF-ELSE 子句
- java - 将按钮上的回收站视图滚动到特定位置
- mysql - 看不到将 nvarchar 转换和格式化为我所需的日期时间
- javascript - React & Mobx .map() 在 onChange 上不起作用
- node.js - 通过 https 代理的 https 请求,但返回“未知协议:openssl”错误
- python - 没有显示 Django 表单