层叠下拉MVC的问题



我在一个表单上有两个下拉菜单(加上其他元素)

<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 locationId的改变会改变RoomId的值。

我有这个Java脚本

<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>

调用控制器

中的代码
[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"));
}

我得到了下拉列表中我期望的元素数(3)但它们都说未定义。我不明白为什么。

提前感谢您的帮助。

马特

响应数据是驼峰大小写格式,因此您需要更改下面的代码:

$("#RoomId").append('<option value="' + room.value  + '">' +    
room.text  + '</option>');                        
// here we are adding option for States    
});  

最新更新