I am retrieving two lists from a sql db (entity and location). When an entity is selected, this filters the location values to just those values that belong to the selected entity. This works fine when creating an entry or when changing the entity, the new location fields populate correctly. However, when I go to edit an existing record, the correct location is selected, but it also displays all of the locations for all entities, not just for the selected entity. I don't want the user to accidently select a location that belongs to a different entity.
I will use Corning Hospital as an example. It has two locations, cafeteria and gazebo 2.
When the user tries to edit an existing record, it does select the correct location item (gazebo 2), but it also contains location items for all the other entities as well.
Here is my razor edit page
<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>
Here is where the location is able to be filtered on an onchange event
$(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();
}
You need change OnGet
method here to display corresponding Location with current EntityId:
ViewData["LocationID"] = new SelectList(locations.Where(a => a.Active == "Y" & a.EntityID==SecurityLog.EntityID), "ID", "Name");