【问题标题】:How to create Cascading Dropdown如何创建级联下拉菜单
【发布时间】:2022-08-11 23:59:38
【问题描述】:

如何使用 Ajax 错误处理创建级联下拉菜单

创建下拉国家和地区

1.当我点击国家它显示状态。

2.当我点击状态它显示区。

public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
    }

public class District
    {
        public int DistrictId { get; set; }
        public string DistrictName { get; set; }
    }

public class State
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
    }

控制器

namespace Dropdown.Controllers
{
    public class CascadingController : Controller
    {
        private readonly DropdownContext _context;

        public CascadingController(DropdownContext context)
        {
            _context = context;
        }

        public IActionResult Index()
       {
            return View();
       }
       public IActionResult DropDown()
       {
            ViewBag.Country = _context.Country.ToList();
            ViewBag.District = _context.District.ToList();
            ViewBag.State = _context.State.ToList();
            return View();
       }
    }
}

这是我的结合课

public class Combine
    {
        public int CombineId { get; set; }
        public int CountryId { get; set; }
        public int StateId { get; set; }
        public int DistrictId { get; set; }

        public Country Country { get; set; }
        public State State { get; set; }
        public District District { get; set; }
    }

看法

这是查看页面我只添加表单 html 以显示下拉列表我不添加 jQuery 或其他东西

@model Dropdown.Models.Combine
@{
    ViewData[\"Title\"] = \"DropDown\";
}
<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"></script>
<html>
<head>
</head>
<body>
    <h1>DropDown</h1>
    <hr />

    <form>
        <div class=\"row\">
            <div class=\"col-md-4\">
                <div class=\"form-group\" style=\"padding-top: 8px;padding-right:7px;\">
                    <label asp-for=\"Country\" class=\"control-label\"></label>
                    <br />
                    <select asp-for=\"CountryId\" class=\"form-control\" asp-items=\"@(new SelectList(ViewBag.Country,\"CountryId\",\"CountryName\"))\">
                    </select>
                </div>
                <br />

                <div class=\"form-group\" style=\"padding-top: 8px;padding-right:7px;\">
                    <label asp-for=\"District\" class=\"control-label\"></label>
                    <br />
                    <select asp-for=\"DistrictId\" class=\"form-control\" asp-items=\"@(new MultiSelectList(ViewBag.District,\"DistrictId\",\"DistrictName\"))\">
                    </select>
                </div>
                <br />
                <div class=\"form-group\" style=\"padding-top: 8px;padding-right:7px;\">
                    <label asp-for=\"State\" class=\"control-label\"></label>
                    <br />
                    <select asp-for=\"StateId\" class=\"form-control\" asp-items=\"@(new SelectList(ViewBag.State,\"StateId\",\"StateName\"))\">
                    </select>
                </div>

                <br />

                <input type=\"submit\" value=\"Create\" class=\"btn btn-primary form-group\" />


            </div>
        </div>
    </form>

</body>
</html>


<br>

<div>
    <a asp-action=\"Index\">Back to List</a>
</div>

@section Scripts {
    <script><script type=\"text/javascript\">
    </script>
    @{await Html.RenderPartialAsync(\"_ValidationScriptsPartial\");}
}

enter image description here

  • 你能分享你的控制器并查看代码吗?
  • 感谢您的更新,现在可以方便地处理此问题。
  • 你的问题不是很清楚。第 1 点和第 2 点是您面临的问题还是您希望达到的结果?
  • 你能分享一张目前正在展示的图片吗?
  • 我已经添加了有问题的图片链接

标签: c# asp.net-mvc asp.net-core asp.net-core-mvc


【解决方案1】:

如何使用 Ajax 错误处理创建级联下拉菜单?

模型应该是:

public class Country
        {
            public int CountryId { get; set; }
            public string? CountryName { get; set; }
        }
        public class State
        {
            public int StateId { get; set; }
            public string StateName { get; set; }
            public int CountryId { get; set; }
        }
        public class District
        {
            public int DistrictId { get; set; }
            public string DistrictName { get; set; }
            public int StateId { get; set; }
        }

笔记:由于State 依赖于Country,因此在State 上添加了CountryId 引用,StateDistrict 也是如此。

虚拟数据:

public static List<Country> ListOfCountry = new List<Country>()
        {
            new Country() { CountryId =101, CountryName ="INDIA", },
            new Country() { CountryId =102, CountryName ="USA", }, 
            new Country() { CountryId =103, CountryName ="UK", }
        };
        public static List<State> ListOfState = new List<State>()
        {
            //INDIA
            new State() { CountryId =101, StateId =1, StateName = "Delhi" }, 
            new State() { CountryId =101, StateId =2, StateName = "Haydrabad" }, 
            new State() { CountryId =101, StateId =3, StateName = "Pune" }, 
            //USA
            new State() { CountryId =102, StateId =4, StateName = "New York" },
            new State() { CountryId =102, StateId =5, StateName = "Silicon Valley" },
            new State() { CountryId =102, StateId =6, StateName = "Dallaus" },
            //UK
            new State() { CountryId =103, StateId =7, StateName = "London" },
            new State() { CountryId =103, StateId =8, StateName = "Cardif" },
            new State() { CountryId =103, StateId =9, StateName = "Sundarland" },
        };
        public static List<District> ListOfDistrict = new List<District>()
        {
            //INDIA
            new District() { DistrictId =101, StateId =1, DistrictName = "District Of Delhi" },
            new District() { DistrictId =101, StateId =2, DistrictName = "District Of Haydrabad" },
            new District() { DistrictId =101, StateId =3, DistrictName = "District Of Pune" }, 
            //USA
            new District() { DistrictId =102, StateId =4, DistrictName = "District Of New York" },
            new District() { DistrictId =102, StateId =5, DistrictName = "District Of Silicon Valley" },
            new District() { DistrictId =102, StateId =6, DistrictName = "District Of Dallaus" },
            //UK
            new District() { DistrictId =103, StateId =7, DistrictName = "District Of London" },
            new District() { DistrictId =103, StateId =8, DistrictName = "District Of Cardif" },
            new District() { DistrictId =103, StateId =9, DistrictName = "District Of Sundarland" },
        };

笔记:您可以将此虚拟数据放在controlleraction 上方。您甚至可以从数据库中获取数据。请看下面的截图:

控制器:

  public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public async Task<ActionResult> LoadCountry()
        {
            var country = ListOfCountry.ToList();
            
            return Ok(country);
           
        }

        [HttpGet]
        public async Task<ActionResult> GetState(int countryId)
        {
            var state = ListOfState.Where(cId => cId.CountryId == countryId).ToList() ;

            return Ok(state);

        }

        [HttpGet]
        public async Task<ActionResult> GetDistrict(int stateId)
        {
            var state = ListOfDistrict.Where(cId => cId.StateId == stateId).ToList();

            return Ok(state);

        }


    [HttpPost]
    public async Task<IActionResult> AddCountryStateDistrict(SubmitModel model)
    {
       
        return RedirectToAction("Index");
    }

意见:

        <div class="form-group">
            <label class="col-md-4 control-label">Country</label>
            <div class="col-md-6">
                <select class="form-control" id="ddlCountry"></select><br />
            </div>
        </div>

        <div class="form-group">
            <label class="col-md-4 control-label">State</label>
            <div class="col-md-6">
                <select class="form-control" id="ddlState"></select>
                <br />

            </div>
        </div>
        <br />
        <div class="form-group">
            <label class="col-md-4 control-label">District</label>
            <div class="col-md-6">
                <select class="form-control" id="ddlDistrict"></select>

            </div>
        </div>
           <div class="form-group">
            <label class="col-md-4 control-label"></label>
            <div class="col-md-6">
                 <input id="Submit" value="Submit" class="btn btn-primary" />

            </div>
        </div>
    </div>
    <div class="col-lg-3"></div>
   
   
</div>

脚本:

@section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>

    $(document).ready(function () {

       var ddlCountry = $('#ddlCountry');
    ddlCountry.append($("<option></option>").val('').html('Please Select Country'));
    $.ajax({
        url: 'http://localhost:5094/CascadingDropdown/LoadCountry',
        type: 'GET',
        dataType: 'json',
        success: function (d) {
            console.log(d);
            $.each(d, function (i, country) {
                console.log(i);
                console.log(country);

                ddlCountry.append($("<option></option>").val(country.countryId).html(country.countryName));
            });
        },
        error: function () {
            alert('Error!');
        }
    });

    //State details by country id

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

        //alert("On ddlCountry change");
        var CountryId = parseInt($(this).val());
        console.log(CountryId);
        if (!isNaN(CountryId)) {
            var ddlState = $('#ddlState');
            ddlState.empty();
            ddlState.append($("<option></option>").val('').html('Please wait ...'));


            $.ajax({
                url: 'http://localhost:5094/CascadingDropdown/GetState',
                type: 'GET',
                dataType: 'json',
                data: { CountryId: CountryId },
                success: function (d) {

                    ddlState.empty(); // Clear the please wait
                    ddlState.append($("<option></option>").val('').html('Select State'));
                    $.each(d, function (i, states) {
                        ddlState.append($("<option></option>").val(states.stateId).html(states.stateName));
                    });
                },
                error: function () {
                    alert('Error!');
                }
            });
        }


    });

    //District Bind By satate id
    $("#ddlState").change(function () {
        var StateId = parseInt($(this).val());
        if (!isNaN(StateId)) {
            var ddlDistrict = $('#ddlDistrict');
            ddlDistrict.append($("<option></option>").val('').html('Please wait ...'));
            $.ajax({
                url: 'http://localhost:5094/CascadingDropdown/GetDistrict',
                type: 'GET',
                dataType: 'json',
                data: { stateId: StateId },
                success: function (d) {


                    ddlDistrict.empty(); // Clear the plese wait
                    ddlDistrict.append($("<option></option>").val('').html('Select District Name'));
                    $.each(d, function (i, districts) {
                        ddlDistrict.append($("<option></option>").val(districts.districtId).html(districts.districtName));
                    });
                },
                error: function () {
                    alert('Error!');
                }
            });
        }


    });

    //On Submit Method
    
        $("#Submit").click(function(){
               var ddlCountry =  parseInt($("#ddlCountry").val());
               var ddlState =  parseInt( $("#ddlState").val());
               var ddlDistrict =  parseInt($("#ddlDistrict").val());
               
               var data = {
                ddlCountry: ddlCountry,
                ddlState: ddlState,
                ddlDistrict: ddlDistrict
                
            };
             console.log(data);
                  $.ajax({
                    url: 'http://localhost:5094/CascadingDropdown/AddCountryStateDistrict',
                    type: 'POST',
                    dataType: 'json',
                    data: data,
                    success: function (d) {
                       alert("Submitted To Database");
                    },
                    error: function () {
                        alert('Error!');
                    }
                });
                
        });

    });
</script>
        }

输出:

【讨论】:

  • 是的,非常感谢
  • 这些非常有用。 +1
  • 感谢您的反馈。很高兴能在这方面提供帮助。
猜你喜欢
  • 2013-09-22
  • 2021-03-10
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-02
  • 2018-04-25
  • 2013-09-14
相关资源
最近更新 更多