级联下拉列表不会在编辑期间显示已保存的值

时间:2017-06-09 02:46:25

标签: javascript asp.net-mvc cascadingdropdown

我正在为我的项目使用级联下拉列表。它适用于“创建”页面,所选值已保存在数据库中。但在编辑模式下,保存的值不会显示在下拉列表中。

编辑视图

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

任何帮助将不胜感激。 谢谢。 :)

0 个答案:

没有答案