I have two drop downs on an form (plus other elements)
<div class="form-group row">
<div class="col-4">
<label asp-for="job.LocationId"></label>
</div>
<div class="col-8">
<select asp-for="job.LocationId" id="LocationId" name="LocationId"
asp-items="@Model.LocationList" class="form-select">
<option disabled selected>--Select Location--</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label asp-for="job.RoomId"></label>
</div>
<div class="col-8">
<select id="RoomId" name="RoomId" asp-for="job.RoomId"
asp-items="@(new SelectList(string.Empty, "Value", "Text"))" class="form-select">
</select>
</div>
</div>
a Change in locationId should change the values in RoomId.
I have this Java script
<script>
$(document).ready(function () {
$('#LocationId').change(function () {
$("#RoomId").empty();
$.ajax({
type: 'GET',
url: '@Url.Action("GetRooms")', // we are calling json method
dataType: 'json',
data: { locationId: $('#LocationId Option:Selected').val() },
// here we are get value of selected country and passing same value as inputto json method GetStates.
success: function (rooms) {
// states contains the JSON formatted list
// of states passed from the controller
$.each(rooms, function (i, room) {
$("#RoomId").append('<option value="' + room.Value + '">' +
room.Text + '</option>');
// here we are adding option for States
});
},
error: function (ex) {
alert('Failed to retrieve rooms.' + ex);
}
});
return false;
})
});
</script>
which calls this code in the controller
[HttpGet]
public JsonResult GetRooms(string locationId)
{
int.TryParse(locationId, out int LocID);
List<SelectListItem> rooms = new List<SelectListItem>();
rooms.Add(new SelectListItem { Text = "-- Select Room --", Value = "0" });
IEnumerable<Room> roomList = _unitOfWork.Room.GetAll(r => r.LocationId == LocID);
foreach (Room room in roomList)
{
rooms.Add(new SelectListItem { Text = room.RoomName, Value = room.Id.ToString() });
}
//roomList.Insert(0, new Room { Id = 0, LocationId = LocID, RoomName = "-- Select Room --", RoomVolume =0 });
var list = Json(new SelectList(rooms, "Value", "Text"));
return Json(new SelectList(rooms, "Value", "Text"));
}
which all works I get back the number of elements I expect in the drop down (3) but they all say undefined. I can't figure out why.
Thanks in advance for your help.
Matt
The response data is camel case format, so you need change the code below:
$("#RoomId").append('<option value="' + room.value + '">' +
room.text + '</option>');
// here we are adding option for States
});