C# ASP. NET Ссылка ядра sh Раскрывающийся список - PullRequest
1 голос
/ 19 июня 2020

Я пытаюсь обновить sh Комбо при изменении другого выбора Комбо. Две комбинации не связаны и не зависят друг от друга.

Я пытаюсь сделать каждый раз, когда DropDownListFor TypeOfServiceId изменяется, я хочу обновить sh - Повторно заполнить DropDownListFor LevelDegreeId

Я использую generi c метод заполнения DropDownListFor.

Вот мой код для заполнения раскрывающихся списков:

public IEnumerable<SelectListItem> GetDropDownList<O>(string text, string value, 
                                                     Expression<Func<O, bool>> filter = null) 
                                                     where O : class
{
    IEnumerable<O> result = _dbContext.Set<O>();

    if (filter != null)
    {
        result = result.AsQueryable().Where(filter);
    }

    var query = from e in result
                select new
                {
                    Value = e.GetType().GetProperty(value).GetValue(e, null),
                    Text = e.GetType().GetProperty(text).GetValue(e, null)
                };

    return query.AsEnumerable()
        .Select(s => new SelectListItem
        {
            Value = s.Value.ToString(),
            Text = s.Text.ToString()
        });
}

В контроллере у меня есть метод AddEdit с именем Upsert

public IActionResult Upsert(int? id)
{
    ServicesVM = new ServicesVM()
    {
        Services = new Services(),
        DepartmentList = _repository.GetDropDownList<Department>("DepartmentName", "Id"),
        TypeOfServicList = _repository.GetDropDownList<TypeOfService>("Description", "Id"),
        LevelDegreeList = _repository.GetDropDownList<LevelDegree>("LevelDegreeFull", "Id"),
        TaxList = _repository.GetDropDownList<Tax>("VatName", "Id")
    };

    if (id != null)
    {
        ServicesVM.Services = _repository.Get(id.GetValueOrDefault());
    }

    return View(ServicesVM);
}

Вот часть из Upsert View

@model School.Models.ViewModels.ServicesVM

@{
    var title = "Add New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<form method="post" asp-action="Upsert">
    <div class="row">

        @await Component.InvokeAsync("HeaderName", new { name = "Services" })



        @if (Model.Services.Id != 0)
        {
            <input type="hidden" asp-for="Services.Id" />

            title = "Edit record";
        }

        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">@title</h3>
                </div>
                <div class="card-body col-6">
                    <div class="form-group row">
                        <div class="col-4">
                            <label asp-for="Services.TypeOfServiceId"></label>
                        </div>
                        <div class="col-8">
                            @Html.DropDownListFor(m => m.Services.TypeOfServiceId, Model.TypeOfServicList,
                                                    "- Please Select -", new { @class = "form-control" })
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-4">
                            <label asp-for="Services.LevelDegreeId"></label>
                        </div>
                        <div class="col-8">
                            @Html.DropDownListFor(m => m.Services.LevelDegreeId, Model.LevelDegreeList,
                                                    "- Please Select -", new { @class = "form-control" })
                        </div>
                    </div>

Я пробовал это, но безуспешно:

loadLevelDegree: function () {
    $.ajax({

        url: "/admin/service/GetLevelDegree",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        success: function (data) {
            $(data).each(function () {
                $("#Services_LevelDegreeId").append($("<option></option>").val(this.Value).html(this.Text));
            });
        },
        error: function (data) { }
    });
}

Это мое действие GetLevelDegree

public IActionResult GetLevelDegree()
{
    return Json(new { data = _repository.GetDropDownList<LevelDegree>("LevelDegreeFull", "Id") });
}

1 Ответ

1 голос
/ 22 июня 2020

Данные возврата в ajax содержат два слоя, измените их, как показано ниже:

loadLevelDegree: function () {
    $.ajax({
        url: "/admin/service/GetLevelDegree",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        success: function (data) {
            $("#Services_LevelDegreeId").empty();
            $("#Services_LevelDegreeId").append($("<option>- Please Select -</option>"));
            $(data.data).each(function () {
                $("#Services_LevelDegreeId").append($("<option></option>").val(this.value).html(this.text));
            });
        },
        error: function (data) { }
    });
}
...