본문 바로가기
ASP.NET MVC

ASP.NET MVC] Sub Select Option 동적 변경

by Fastlane 2022. 5. 27.
728x90
반응형

cshtml

<select class="customSelect" id="branch" name="branch">
     <option value="">소속</option>
     <option value="경기도지사">경기도지사</option>
     <option value="강원도지사">강원도지사</option>
</select>

<select class="customSelect" id="emp_name" name="emp_name">
     <option value="">담당자명</option>
</select>

branch select가 변경될 때, 소속 담당자리스트를 가져와서 option을 동적으로 생성해주도록 하자. 

    $(document).ready(function () {

        $("#branch").change(function () {

            fn_setBranchEmpList($(this).val(),'담당자명');

        });
    });
    
    

    function fn_setBranchEmpList(selected_branch, selected_emp) {

        var jsonData = JSON.stringify({ branch: selected_branch });

        $.ajax({
            type: 'POST',
            url: "/Member/GetEmpListByBranchName",
            contentType: "application/json",
            data: jsonData,
            dataType: 'json',
            cache: false,
            async: true,
            complete: function () {
            },
            success: function (result) {

                var options = document.querySelectorAll('#emp_name option');
                options.forEach(o => o.remove());

                var s = document.getElementById('emp_name');
                s.append(new Option('담당자명', ''));

                result.result.forEach(function (element, index) {
                    if (element == selected_emp) {
                        var option = new Option(element, element, false, true);
                        s.append(option);
                    } else {
                        var option = new Option(element, element);
                        s.append(option);
                    }
                });

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                alert('에러가 발생하였습니다.고객센터에 문의해주세요.');
            }
        });
    }

 

Controller


        [HttpPost]
        public JsonResult GetEmpListByBranchName(string branch)
        {
            List<string> result = new List<string>();
            string errMsg = string.Empty;

            try
            {
                result = MemberDa.Get_EmpListByBranchName(branch).ToList();
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }

            return Json(new { result = result, errMsg = errMsg });

        }

 

728x90
반응형

댓글