I am working on a asp.net mvc project and I need to filter dropdownlist according to what user has selected first dropdownlist
This is my first dropdownlist in view:
<div class="form-group">
@Html.LabelFor(m => m.BuildDefinitionName, "Build Definition name", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.BuildDefinitionName, new SelectList(Model.BuildData.Select(x => x.Key), "BuildInfo"), "select", new { @class = "form-control" })
</div>
</div>
and this is my second dropdownlist:
<div class="form-group">
@Html.LabelFor(m => m.CurrentBuildNumber, "Current Build", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.CurrentBuildNumber, new SelectList(Model.BuildData
.Where(x=>x.Key == "#BuildDefinitionName")
.Select(y => y.Value), "BuildInfo"), "select", new { @class = "form-control" })
</div>
</div>
I have a dictionary that key is string (what the user should chose first dropdown ) and value is IEnumerable ( what it should be filtered by the first dropdown selection).
I am so thanksful for solving my problem.
You need to use jquery to modify the second dropdown list.
Model.BuildData
. So, in your controller, be sure to provide all the records because we will be filtering on client-side.public ActionResult ControllerName(){
var yourModel = new yourModel();
// Add all the entries to Build Data, we're going to filter it with jquery
yourModel.BuildData = db.BuildData.ToList();
return View(yourModel);
}
<div class="form-group">
@Html.LabelFor(m => m.CurrentBuildNumber, "Current Build", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
<select id="CurrentBuildNumber" name="CurrentBuildNumber" class="form-control">
@foreach(var selectItem in Model.BuildData){
<option data-filter="@selectItem.Key" value="@selectItem.Value">
@selectITEM.Value
</option>
}
</select>
</div>
</div>
The code below will loop through all the options in the 2nd dropdown list, and if its data-attribute doesn't match with the selected value, it will hide it.
<script>
$(document).ready(function(){
$(document).on("change","#BuildDefinitionName",function(){
var selected = $(this).val();
$("#CurrentBuildNumber").find("options").each(function(){
if($(this).data("filter")==selected){
// if data-filter is the same as the selected value, show it
$(this).show();
}else{
// if it doesn't match, hide
$(this).hide();
}
});
});
});
</script>