In My view code two dropdownlist "Area" and "GatepassCategory". In
"Area" automatically set selected value on load. But in
"GatepassCategory" dropdown it is not loaded.
Well, based on your shared code snippet and description it seems that your GatepassCategory dropdown value has not been loaded. There might be numerous reasons for that but according to your scenario, I cannot see how you are calling CheckGatepassvaluevalid
method which is important.
Apart from that, you should call relevant controller to fetch your GatePassCategory data as well.
How to resolve:
Let s have a look how can we load the area dropdown and on its change event how can we load subsequent dropdown.
Demo Model:
public class GatePass
{
public int Id { get; set; }
public string Name { get; set; }
public string Area { get; set; }
}
Load Area Controller Action:
public IActionResult LoadArea()
{
List<SelectListItem> areaList = new List<SelectListItem>();
areaList.Add(new SelectListItem { Text = "Area-A", Value = "Area-A" });
areaList.Add(new SelectListItem { Text = "Area-B", Value = "Area-B" });
areaList.Add(new SelectListItem { Text = "Area-C", Value = "Area-C" });
ViewBag.ListAreas = areaList;
return View();
}
Gate Pass Dropdown Value Load Controller Action:
[HttpPost]
public IActionResult CheckPassByArea(string areaId)
{
var gatePass = new List<GatePass>()
{
new GatePass {Id = 1,Name = "Gete-A", Area = "Area-A"},
new GatePass {Id = 2,Name = "Gete-B", Area = "Area-B"},
new GatePass {Id = 3,Name = "Gete-C", Area = "Area-C"},
};
SelectList gatePassList = new SelectList(gatePass.Where(ar => ar.Area == areaId), "Id", "Name");
return Json(gatePassList);
}
Note: I am filtering gate pass by selected area in area dropdown.
View:
Area DropDown: @Html.DropDownList("Area", ViewBag.ListAreas, null, new { @class = "form-control", @onchange = "CheckGatePassValue(this.value)" })
<hr />
Gate Pass Dropdown: <select id="GatePass" name="GatePass" class="form-control"></select>
<script language="javascript" type="text/javascript">
function CheckGatePassValue(areaId) {
alert(areaId);
var procemessage = "<option value= 0 > Please wait...</option>";
$("#GatePass").html(procemessage).show();
var url = @Url.Action("CheckPassByArea", "ControllerName") ;
$.ajax({
url: url,
data: { areaId: areaId },
cache: false,
type: "POST",
success: function (data) {
console.log(data);
var markup = "<option value= 0 >Select Gate Pass</option>";
for (var x = 0; x < data.length; x++) {
markup += <option value=" + data[x].value + "> + data[x].text + </option> ;
}
$("#GatePass").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
Note: As you can see I am loading gate pass dropdown based on area name thus, I am calling CheckGatePassValue(this.value) with parameter. If you do not have any param you can just call it by CheckGatePassValue() with no parameter.
Output: