Kaskadowe DropDownList w ASP.NET Core MVC

0

Witam,
Prośba do forumowiczów o wskazanie, gdzie popełniam błąd. Opis fragmentu projektu:
Trzy tabele: 1. Employment 2. Office 3. Department
I teraz próbuje w w kontrolerze Employments w akcji Create stworzyć dwa DropDownList, gdzie pole Department będzie zależne od wyboru w polu Office. Projekt się kompiluje, ale DropDownList Department niestety nie działa :(
Znalazłem bardzo fajne rozwiązanie //www.c-sharpcorner.com/article/creating-simple-cascading-dropdownlist-in-asp-net-core-mvc-with-new-tag-helpers/
Gdzieś robię błąd, ale niestety drugi dzień z rzędu go nie znajduje.

Kontroler:

public class EmploymentsController : Controller
    {
        private readonly SZZPContext _context;

        public EmploymentsController(SZZPContext context)
        {
            _context = context;
        }      

        // GET: Employments/Create
        public IActionResult Create()
        {
            List<Office> officessList = new List<Office>();

            //Getting Data form Database Using EntityFrameworkCore
            officessList = (from office in _context.Offices
                           select office).ToList();

            //Inserting Select Item in List
            officessList.Insert(0, new Office { IDOffice = 0, NameOffice = "Wybierz biuro" });

            //Assigning officessList to ViewBag.ListofOffice

            ViewBag.ListofOffice = officessList;

            PopulateStatusesDropDownList();
            PopulatePositionsDropDownList();

            return View();
        }

        // POST: Employments/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("IDEmployment,Name,Surname,NrSap,DateEmployment,EndContract,IDOffice,OfficeSymbol,IDDepartment,IDPosition,IDStatus")] Employment employment, FormCollection formCollection)
        {
            //Validation
            if (ModelState.IsValid)
            {
                _context.Add(employment);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            //Getting selected Value
            var IDDepartment = HttpContext.Request.Form["IDDepartment"].ToString();

            //Setting Data back to ViewvBag after Posting Form
            List<Office> officessList = new List<Office>();
            officessList = (from office in _context.Offices
                           select office).ToList();
            officessList.Insert(0, new Office { IDOffice = 0, NameOffice = "Wybierz biuro" });

            //Assigning officessList to ViewBag.ListofOffice
            ViewBag.ListofOffice = officessList;

            PopulateStatusesDropDownList(employment.IDStatus);
            PopulatePositionsDropDownList(employment.IDPosition);

            return View(employment);
        }

        private void PopulateStatusesDropDownList(object selectedStatus = null)
        {
            var statusesQuery = from s in _context.Statuses
                                orderby s.IDStatus
                                select s;
            ViewBag.IDStatus = new SelectList(statusesQuery.AsNoTracking(),"IDStatus", "NameStatus", selectedStatus);
        }

        private void PopulatePositionsDropDownList(object selectedPosition = null)
        {
            var positionsQuery = from p in _context.Positions
                                 orderby p.IDPosition
                                 select p;
            ViewBag.IDPosition = new SelectList(positionsQuery.AsNoTracking(), "IDPosition", "NamePosition", selectedPosition);
        }

        public JsonResult GetDepartment (int IDOffice)
        {
            List<Department> departmentsList = new List<Department>();

            //Getting Data from Database Using EntityFramework
            departmentsList = (from department in _context.Departments
                              where department.IDOffice == IDOffice
                              select department).ToList();

            //Inserting Select Item in List
            departmentsList.Insert(0, new Department { IDDepartment = 0, NameDepartment = "Wybierz wydział" });

            return Json(new SelectList(departmentsList, "IDDepartment", "DepartmentName"));

        }

    }
}

Widok:

@model SZZP2._2.Models.Employment
@{
    <script src="~/lib/jquery/dist/jquery.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {
            var items = "<option value='0'>Wybierz wydział</option>";
            $('#IDDepartment').html(items);
        });
    </script>

    <script type="text/javascript">
    $(document).ready(function () {
        $('#IDOffice').change(function () {
            var url = '@Url.Content("~/")' + "Employments/GetDepartment";
            var ddlsource = "#IDOffice";
                $.getJSON(url, { id: $(ddlsource).val() }, function (data) {
                    var items = '';
                    $("#IDDepartment").empty();
                    $.each(data, function (i, department) {
                        items += "<option value='" + department.value + "'>" + department.text + "</option>";
                    });
                    $('#IDDepartment').html(items);
                });
        });
    });
    </script>

}
<!--ViewData["Title"] = "Create";-->


<h2>Zatrudnianie nowego pracownika</h2>

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-controller="Employments" asp-action="Create" method="post" role="form">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Surname" class="control-label"></label>
                <input asp-for="Surname" class="form-control" />
                <span asp-validation-for="Surname" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="NrSap" class="control-label"></label>
                <input asp-for="NrSap" class="form-control" />
                <span asp-validation-for="NrSap" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DateEmployment" class="control-label"></label>
                <input asp-for="DateEmployment" class="form-control" />
                <span asp-validation-for="DateEmployment" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="EndContract" class="control-label"></label>
                <input asp-for="EndContract" class="form-control" />
                <span asp-validation-for="EndContract" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="IDOffice" class="control-label"></label>
                <select asp-for="IDOffice" class="form-control"
                        asp-items="@(new SelectList(@ViewBag.ListofOffice, "IDOffice", "NameOffice"))"></select>
            </div>

            <div class="form-group">
                <label asp-for="IDDepartment" class="control-label"></label>
                <select class="form-control" id="IDDepartment" name="IDDepartment" asp-for="IDDepartment"
                        asp-items="@(new SelectList(string.Empty,"IDDepartment", "DepartmentName"))"></select>
            </div>

            <div class="form-group">
                <label asp-for="IDPosition" class="control-label"></label>
                <select asp-for="IDPosition" class="form-control" asp-items="ViewBag.IDPosition"></select>
                @*<span asp-validation-for="IDPosition" class="text-danger"></span>*@
            </div>
            <div class="form-group">
                <label asp-for="IDStatus" class="control-label"></label>
                <select asp-for="IDStatus" class="form-control" asp-items="ViewBag.IDStatus"></select>
                @*<span asp-validation-for="IDStatus" class="text-danger"></span>*@
            </div>
            <div class="form-group">
                <input type="submit" value="Zatrudnij" class="btn btn-success" />
            </div>
        </form>
    </div>
</div>
0

Ale co konkretnie nie działa? Wypełnienie selecta czy może próba zmiany Office? A może też debug nie działa? A console.log() działa ?

0
szydlak napisał(a):

Ale co konkretnie nie działa? Wypełnienie selecta czy może próba zmiany Office? A może też debug nie działa? A console.log() działa ?

Biura wybierają się prawidłowo. Select z wydziałami się nie wypełnia.

Show output from Debug:
> Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/2.0 GET https://localhost:44333/Employments/GetDepartment?id=12  
> Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "GetDepartment", controller = "Employments"}. Executing action SZZP2._2.Controllers.EmploymentsController.GetDepartment (SZZP2.2)
> Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executing action method SZZP2._2.Controllers.EmploymentsController.GetDepartment (SZZP2.2) with arguments (0) - Validation state: Valid
> Microsoft.EntityFrameworkCore.Infrastructure:Information: Entity Framework Core 2.2.4-servicing-10062 initialized 'SZZPContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
> Microsoft.EntityFrameworkCore.Database.Command:Information: Executed DbCommand (4ms) [Parameters=[@__IDOffice_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
> SELECT [department].[IDDepartment], [department].[IDOffice], [department].[NameDepartment], [department].[SymbolDeprtament]
> FROM [Department] AS [department]
> WHERE [department].[IDOffice] = @__IDOffice_0
> Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method SZZP2._2.Controllers.EmploymentsController.GetDepartment (SZZP2.2), returned result Microsoft.AspNetCore.Mvc.JsonResult in 35.6607ms.
> Microsoft.AspNetCore.Mvc.Formatters.Json.Internal.JsonResultExecutor:Information: Executing JsonResult, writing value of type 'Microsoft.AspNetCore.Mvc.Rendering.SelectList'.

Prośba o wyrozumiałość jeżeli pytam o coś oczywistego, ale początkuje w temacie, a już JavaScript jest przeze mnie bardzo słabo przyswojony :(
Domyślam się, że źle przekazuje IDOffice do metody GetDepartment???

0
cordial_spook napisał(a):

Prośba o wyrozumiałość jeżeli pytam o coś oczywistego, ale początkuje w temacie, a już JavaScript jest przeze mnie bardzo słabo przyswojony :(
Domyślam się, że źle przekazuje IDOffice do metody GetDepartment???

Ale my jesteśmy wyrozumiali tylko jak masz problem to opisz go w miarę szczegółowo a nie sam kod. Ale do rzeczy. Więc jeśli nie wypełniają się to najpierw sprawdź czy jak wybierzesz Office to czy wchodzi do kontrollera. Czyli postawm breake pointa. Jeśli nie wchodzi to masz problem z JSem. Czyli sprawdzasz czy zdarzenie jest podpięte i robisz w kodzie on change jakiś console.log("TEst");

Jak się wyświetli to sprawdzaj czy odpowiednio pobierasz ID z tego selecta (też wyświetl sobie na consoli) a potem sprawdzaj czy budujesz dobrze request do backendu

1 użytkowników online, w tym zalogowanych: 0, gości: 1