I am using cascading dropdown list for my project. It is working fine for Create page and the values selected was saved in the database. But during the Edit mode, the saved value is not displayed in the dropdown.
EDIT VIEW
<div class="form-group">
@Html.LabelFor(model => model.CatID, "Category", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("CatID", ViewBag.CatID as SelectList, "--SELECT CATEGORY--", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CatID, "*", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.NocID, "Nature of Occurrence", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("NocID", new SelectList(string.Empty, "Value", "Text"), htmlAttributes: new { @class = "form-control dropdown1" })
@Html.ValidationMessageFor(model => model.NocID, "*", new { @class = "text-danger" })
</div>
</div>
JAVASCRIPT
<!--Cascading Dropdown for Category and Nature of Occurrence-->
<script type="text/javascript">
$(document).ready(function () {
//Category Dropdown Selectedchange event
$("#CatID").change(function () {
$("#NocID").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetNoCs")',
dataType: 'json',
data: { id: $("#CatID").val() },
// Get Selected Category ID.
success: function (nocs) {
$("#NocID").append($('<option></option>').val('').text('--SELECT NATURE OF OCCURRENCE--'));
$.each(nocs, function (i, noc) {
$("#NocID").append('<option value ="' + noc.Value + '">' + noc.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve categories.' + ex);
}
});
return false;
})
});
CONTROLLER
// Json Call to get nature of occurrence
public JsonResult GetNoCs(string id)
{
List<SelectListItem> nocs = new List<SelectListItem>();
var nocList = this.Getnoc(new Guid(id));
var nocData = nocList.Select(m => new SelectListItem()
{
Text = m.Title,
Value = m.NocID.ToString(),
});
return Json(nocData, JsonRequestBehavior.AllowGet);
}
// Get Nature of Occurrence from DB by CatID
public IList<nature_of_occurrence_ref> Getnoc(Guid CatID)
{
return db.nature_of_occurrence_ref.Where(m => m.CatID == CatID).ToList();
}
Any help will be greatly appreciated. Thank you. :)