ASP.NET MVC + jQuery – SelectBox with ( Show Common / Show All ) Option
private SoccerEntities entity; public JSONController() { this.entity = new SoccerEntities(); } public ActionResult SelectBoxForm() { List<NATION> AllNationList = this.entity.NATIONs.Where(n => n.NATION_ID != 0).OrderBy(x => x.NATION_NAME).ToList(); List<NATION> CommonNationList = this.entity.NATIONs.Where(n => n.NATION_REGION == 3).OrderBy(x => x.NATION_NAME).ToList(); ViewBag.AllNation = this.ToJson(AllNationList); ViewBag.CommonNation = this.ToJson(CommonNationList); return View(); } public string ToJson(List<NATION> list) { return JArray.FromObject(list).ToString().Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("'", "\'"); } |
<select id="SelectBox" style="margin-top:8px; height:30px; font-weight:bold; color:#000000; font-size:10pt; font-family:Arial; width:250px;"> <option value="">** Please Select **</option> </select> |
var AllNation = JSON.parse('@(Html.Raw(ViewBag.AllNation))'); var CommonNation = JSON.parse('@(Html.Raw(ViewBag.CommonNation))'); $(document).ready(function () { ShowItem($("#SelectBox"), false, CommonNation); $("#SelectBox").change(function () { if ($(this).val() == "Show All") { ShowItem($(this), true, AllNation); } else if ($(this).val() == "Show Common") { ShowItem($(this), false, CommonNation); } }); }); function ShowItem(SelectBoxCtl, ShowAll, ItemCollection) { SelectBoxCtl.empty(); SelectBoxCtl.append($('<option>', { value: "", text: "** Please Select **", style: "font-weight:bold; color:#0000AA;" })); for (var i = 0; i < ItemCollection.length; i++){ SelectBoxCtl.append($('<option>', { value: ItemCollection[i].NATION_ID, text: ItemCollection[i].NATION_NAME, style: "font-weight:bold; color:#000000;" })); } if (ShowAll) { SelectBoxCtl.append($('<option>', { value: "Show Common", text: "** Show Common **", style: "font-weight:bold; color:#0000AA;" })); } else { SelectBoxCtl.append($('<option>', { value: "Show All", text: "** Show All **", style: "font-weight:bold; color:#0000AA;" })); } } |