-->

Tạo Cascading Dropdownlist trong ASP.NET Core MVC

Mình có một thí dụ khi bạn code một trang register và cho người dùng chọn thông tin Tỉnh thành, thành phố, quận huyện,... và nó là một dropdownlist (hay select option). Và người dùng chọn Tỉnh thành, rồi đến quận huyện thì chỉ có quận huyện của thành phố đó hiển thị để bạn chọn.


Bài toán này rất thực tế và hay gặp, mình sẽ hướng dẫn bạn với code làm việc với cả database. Ok, chúng ta cùng bắt đầu nhé.

Tiến hành

Bước 1: Trước tiên, bạn cần Thiết kế cơ sở dữ liệu (database) và tổ chức với 3 bảng sau:

create database DbCountry
go 
use DbCountry
go
create table Country
(
 Id     int identity(1,1) primary key,
 [Name]  nvarchar(100)
)

create table [State]
(
 Id     int identity(1,1) primary key,
 [Name]  nvarchar(100),
 CountryId int
)

create table City
(
 Id     int identity(1,1) primary key,
 [Name]  nvarchar(100),
 StateId   int
)


Sau đó các bạn nhập dữ liệu cho cả 3 bảng vào nhé.

Bước 2: Tạo project ASP.NET Core Web Application với tên là Cascading.Demo

Bước 3: Chọn Web Application (Model - View - Controller).

Bước 4: Cài đặt các NuGet Package sau trong Cascading.Demo:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Relational
  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools


Bước 5: Thêm Connection Strings trong appsetting.json:



"ConnectionStrings": {
    "ConnectionString": "Server=CNPM-PC\\SQLEXPRESS;Database=DbCountry;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

Bạn cần đổi tên Server trên thành tên Server của bạn trong SQL Server.

Bước 6: Vào Tools > NuGet Package Manager > Package Manager Console:


Sau đó nhập command như dưới:

Scaffold-DbContext "Server=CNPM-PC\SQLEXPRESS;Database= DbCountry; user id= sa;password= 123;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Bước 7: Trong Startup.cs tìm đến phương thức ConfigureServices và thêm code sau bên trong phương thức:

services.AddDbContext<DbCountryContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("ConnectionString")));

Bước 8: Tìm đến Controller/HomeController.cs thêm mới các phương thức sau:

public IActionResult Index()
        {
            ViewBag.CountryList = new SelectList(GetCountryList(), "Id", "Name");

            return View();
        }

        public List<Country> GetCountryList()
        {

            DbCountryContext db = new DbCountryContext();

            List<Country> countries = db.Country.ToList();

            return countries;


        }

        public ActionResult GetStateList(int CountryId)
        {
            DbCountryContext db = new DbCountryContext();

            List<State> stateList = db.State.Where(x => x.CountryId == CountryId).ToList();

            ViewBag.StateOptions = new SelectList(stateList, "Id", "Name");

            return PartialView("StateOptionPartial");

        }

        public ActionResult GetCityList(int StateId)
        {
            DbCountryContext db = new DbCountryContext();

            List<City> cityList = db.City.Where(x => x.StateId == StateId).ToList();

            ViewBag.CityOptions = new SelectList(cityList, "Id", "Name");

            return PartialView("CityOptionPartial");

        }

Bước 9: Tạo thư mục mới tên là ViewModel → trong thư mục này tạo mới class tên là CountryAndStateVM.cs và thêm code sau:

namespace Cascading.Demo.ViewModel
{
    public class CountryAndStateVM
    {
        public int CountryId { get; set; }
        public int StateId { get; set; }
        public int CityId { get; set; }
    }
}

Bước 10: Trong Views/Home/Index.cshtml thay thế tất cả thành code sau:

@model Cascading.Demo.ViewModel.CountryAndStateVM
@{
    ViewBag.Title = "Index";
    // Layout = null;
}

<div class="panel panel-body" style="min-height:256px">
    <div class="col-md-9">

        @if (ViewBag.CountryList != null)
        {
            @Html.DropDownListFor(m => m.CountryId, ViewBag.CountryList as SelectList, "-- Select Country--", new { @class = "form-control w-25 mb-3" })

        }
        @Html.DropDownListFor(m => m.StateId, new SelectList(""), "--Select State--", new { @class = "form-control w-25 mb-3" })

        @Html.DropDownListFor(m => m.CityId, new SelectList(""), "--Select City--", new { @class = "form-control w-25 mb-3" })


    </div>

</div>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>

    $(document).ready(function () {

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

            var countryId = $(this).val();
            debugger
            $.ajax({

                type: "Post",
                url: "Home/GetStateList?CountryId=" + countryId,
                contentType:"html",
                success: function (response) {
                  debugger
                    $("#StateId").empty();
                    $("#StateId").append(response);

                }
            })
        })
    })

    $(document).ready(function () {

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

            var stateId = $(this).val();
            debugger
            $.ajax({

                type: "Post",
                url: "Home/GetCityList?StateId=" + stateId,
                contentType:"html",
                success: function (response) {
                  debugger
                    $("#CityId").empty();
                    $("#CityId").append(response);

                }
            })
        })
    })

</script>

Bước 11: Trong Views/Shared → Add 2 views sau:


StateOptionPartial.cshtml

<option value="">--Select State--</option>
@if (ViewBag.StateOptions != null)
{

    foreach (var item in ViewBag.StateOptions)
    {

        <option value="@item.Value">@item.Text </option>

    }

}

CityOptionPartial.cshtml

<option value="">--Select City--</option>
@if (ViewBag.CityOptions != null)
{

    foreach (var item in ViewBag.CityOptions)
    {

        <option value="@item.Value">@item.Text </option>

    }

}

Và như vậy là xong, hãy chạy solution lên và trải nghiệm nhé.


Lời kết

Code trên mình có kết hợp với Ajax để tạo nên, các bước thực hiện rất đơn giản. Nếu gặp phải lỗi thì cmt bên dưới để cùng giải đáp nhé.

Mong bài viết hữu ích, chúc các bạn thành công!

By Hiếu Quốc

Có lẽ bạn thích?

1 comment

Post a Comment