@using OP.WebUI.Areas.Stock.Models @*约定如下: 调用 SetViewBag_Rooms 方法设置 ViewBag.Rooms *@ <div class="form-group"> <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> 所属库房</label> <div class="col-sm-9"> <select id="RoomId" name="RoomId" class="width-40 chosen-select form-control" data-placeholder="所属库房"> @foreach (Father father in (IEnumerable<Father>)ViewBag.Rooms) { if (father.Selected) { <option selected="selected" id="option-@father.Id" value="@father.Id" childs="@father.GetOptionsMark()">@father.Name</option> } else { <option id="option-@father.Id" value="@father.Id" childs="@father.GetOptionsMark()">@father.Name</option> } } </select> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label no-padding-right" for="form-field-1"> 楼层</label> <div class="col-sm-9"> <select id="FloorId" name="FloorId" class="width-40 chosen-select form-control" data-placeholder="楼层"></select> </div> </div> <script type="text/javascript"> var room = $("#RoomId"); room.change(function () { debugger; var roomId = $(this).val(); loadChild(roomId); }); function loadChild(roomId) { if (!roomId) { $("#FloorId").html(""); return; } var childs = $("#option-" + roomId).attr("childs"); $("#FloorId").html(childs); } loadChild(room.val()); </script>
using System.Collections.Generic; using System.Text; namespace OP.WebUI.Areas.Stock.Models { public sealed class Father : Item { public IEnumerable<Child> Items { get; set; } /// <summary> /// 获取下拉选项标记 /// </summary> /// <returns></returns> public string GetOptionsMark() { StringBuilder sb = new StringBuilder(); foreach (var item in Items) { if (item.Selected) { sb.Append("<option selected="selected" value="" + item.Id + "">" + item.Name + "</option>"); } else { sb.Append("<option value="" + item.Id + "">" + item.Name + "</option>"); } } return sb.ToString(); } } public sealed class Child : Item { } public abstract class Item { public int Id { get; set; } public string Name { get; set; } public bool Selected { get; set; } } }
//viewbag 调用示例 //rooms 是 父实体集合 floorsCatch 是子实体数据源 // on room.id = floor.roomid var roomIds = rooms.Select(m => m.Id); var floorsCatch = _floorService.Value.GetFloors(roomIds); ViewBag.Rooms = rooms.Select(m => new Father { Id = m.Id, Name = m.Name, Selected = m.Id == selectedRoomId, Items = floorsCatch.Where(n => n.RoomId == m.Id && n.IsEnable == true) .Select(n => new Child { Id = n.Id, Name = n.Name, Selected = n.Id == selectedFloorId }) });