@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 }) });