ASP.NET MVC Core Cascading DropDownList

asp.net-core-mvc c# entity-framework-core

我在查找教程/視頻時遇到了麻煩,該教程/視頻演示瞭如何使用EntityFramework從數據庫實現Cascading DropDownList。我正在使用ASP.NET MVC Core,EntityFramework Core和C#。

截至目前,我能夠從我的數據庫中檢索數據到我的3 DropDownList罰款。

我希望能夠實現的是讓用戶首先選擇一個州,然後顯示與該州相關的所有城市。然後,在用戶選擇城市後,它將顯示與城市相關的郵政編碼。

任何幫助將不勝感激。

楷模

    public class Customer
{
    public int CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public int StateId { get; set; }
    public int CityId { get; set; }
    public int ZipId { get; set; }

    public State State { get; set; }
    public City City { get; set; }
    public Zip Zip { get; set; }
}

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

    public List<Customer> Customers { get; set; }
}

    public class City
{
    public int CityId { get; set; }
    public string Name { get; set; }

    public int StateId { get; set; }
    public State State { get; set; }

    public List<Customer> Customers { get; set; }
}

    public class Zip
{
    public int ZipId { get; set; }
    public string PostalCode { get; set; }

    public int CityId { get; set; }
    public City City { get; set; }

    public List<Customer> Customers { get; set; }
}

的ViewModels

    public class CustomerFormVM
{
    public int CustomerId { get; set; }

    [Display(Name = "First Name")]
    [StringLength(50)]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [StringLength(50)]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Select State")]
    [Display(Name = "State")]
    public int StateId { get; set; }

    //public IEnumerable<State> States { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }

    [Required(ErrorMessage = "Select City")]
    [Display(Name = "City")]
    public int CityId { get; set; }

    //public IEnumerable<City> Citys { get; set; }
    public IEnumerable<SelectListItem> Citys { get; set; }

    [Required(ErrorMessage = "Select Zip")]
    [Display(Name = "Zip")]
    public int ZipId { get; set; }

    //public IEnumerable<Zip> Zips { get; set; }
    public IEnumerable<SelectListItem> Zips { get; set; }
}

CustomerController

public class CustomerController : Controller
{
    private MultiDbContext db;

    public CustomerController(MultiDbContext context)
    {
        db = context;
    }

    // GET: /<controller>/
    public IActionResult Index()
    {
        return View(db.Customers.ToList());
    }

    public IActionResult getCititesFromDatabaseByStateId(int id)
    {
        return View(db.Citys.Where(c => c.StateId == id).ToList());
    }

    public IActionResult getCities(int id)
    {
        var cities = new List<City>();
        cities = getCititesFromDatabaseByStateId(id); //call repository
        return Json(cities);
    }

    public ActionResult Create()
    {
        var states = db.States.ToList();
        var citys = db.Citys.ToList();
        var zips = db.Zips.ToList();

        var viewModel = new CustomerFormVM
        {
            States = states,
            Citys = citys,
            Zips = zips
        };

        return View(viewModel);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(CustomerFormVM vm)
    {
        if (ModelState.IsValid)
        {
            var customer = new Customer();
            {
                customer.FirstName = vm.FirstName;
                customer.LastName = vm.LastName;
                customer.StateId = vm.StateId;
                customer.CityId = vm.CityId;
                customer.ZipId = vm.ZipId;
            }
            db.Customers.Add(customer);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        else
        {
            vm.States = db.States.ToList();
            vm.Citys = db.Citys.ToList();
            vm.Zips = db.Zips.ToList();
            return View(vm);
        }
    }


    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var customervm = new CustomerFormVM();
        {
            Customer customer = db.Customers.SingleOrDefault(c => c.CustomerId == id);

            if (customer == null)
            {
                return NotFound();
            }

            customervm.CustomerId = customer.CustomerId;
            customervm.FirstName = customer.FirstName;
            customervm.LastName = customer.LastName;

            // Retrieve list of States
            var states = db.States.ToList();
            customervm.States = states;

            // Retrieve list of Citys
            var citys = db.Citys.ToList();
            customervm.Citys = citys;

            // Retrieve list of Citys
            var zips = db.Zips.ToList();
            customervm.Zips = zips;

            // Set the selected state
            customervm.StateId = customer.StateId;

            // Set the selected city
            customervm.CityId = customer.CityId;

            // Set the selected zip
            customervm.ZipId = customer.ZipId;
        }
        return View(customervm);
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CustomerFormVM vmEdit)
    {
        if (ModelState.IsValid)
        {
            Customer customer = db.Customers.SingleOrDefault(c => c.CustomerId == vmEdit.CustomerId);

            if (customer == null)
            {
                return NotFound();
            }

            customer.FirstName = vmEdit.FirstName;
            customer.LastName = vmEdit.LastName;
            customer.StateId = vmEdit.StateId;
            customer.CityId = vmEdit.CityId;
            customer.ZipId = vmEdit.ZipId;

            db.Entry(customer).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(vmEdit);
    }
}

創建視圖

        <div class="form-group">
        @Html.LabelFor(c => c.FirstName)
        @Html.TextBoxFor(c => c.FirstName, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @Html.LabelFor(c => c.LastName)
        @Html.TextBoxFor(c => c.LastName, new { @class = "form-control" })
    </div>

    <div class="form-group">
        @*@Html.LabelFor(s => s.StateId)
            @Html.DropDownListFor(s => s.StateId, new SelectList(Model.States, "StateId", "Abbr"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(s => s.StateId)*@

        <label asp-for="StateId "></label>
        <select asp-for="StateId " asp-items="Model.States" class="form-control" id="state-target"></select>
        <span asp-validation-for="StateId " class="text-danger"></span>
    </div>

    <div class="form-group">
        @*@Html.LabelFor(ct => ct.CityId)
            @Html.DropDownListFor(ct => ct.CityId, new SelectList(Model.Citys, "CityId", "Name"), "", new { @class = "form-control" })
            @Html.ValidationMessageFor(ct => ct.CityId)*@

        <label asp-for="CityId"></label>
        <select asp-for="CityId" asp-items="Model.Citys" class="form-control" id="city-target"></select>
        <span asp-validation-for="CityId" class="text-danger"></span>
    </div>

    <div class="form-group">
        @Html.LabelFor(z => z.ZipId)
        @Html.DropDownListFor(z => z.ZipId, new SelectList(Model.Zips, "ZipId", "PostalCode"), "", new { @class = "form-control" })
        @Html.ValidationMessageFor(z => z.ZipId)
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
}

@section scripts {
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    <script src="~/lib/js/example.js"></script>,
}

熱門答案

我有類似的情況,但在我的例子中我有一個Root文件夾,根據我使用的下一個下拉列表中的哪個根文件夾將顯示相應的子文件夾。

不確定是否有一個純粹的asp.net解決方案但是,我使用了Jquery / Ajax。

您的代碼應如下所示:

HTML列表:

<label asp-for="StateId "></label>
<select asp-for="StateId " asp-items="Model.States" class="form-control" id="state-target"></select>
<span asp-validation-for="StateId " class="text-danger"></span>

<label asp-for="CityId"></label>
<select asp-for="CityId" asp-items="Model.Citys" class="form-control" id="city-target"></select>
<span asp-validation-for="CityId" class="text-danger"></span>

Jquery代碼,你在.js文件中寫這個,然後用這個語句<script src="~/js/example.js"></script>將它添加到一個特定的視圖中,別忘了你需要添加一個jquery在任何其他javascript之前庫到你的項目,你的example.js將包含:

$(document).ready(function () {
  $("#state-target").on("change", function () {
    $list = $("#city-target");
    $.ajax({
        url: "/getCities",
        type: "GET",
        data: { id: $("#state-target").val() }, //id of the state which is used to extract cities
        traditional: true,
        success: function (result) {
            $list.empty();
            $.each(result, function (i, item) {
                $list.append('<option value="' + item["CityId"] + '"> ' + item["Name"] + ' </option>');
            });
        },
        error: function () {
            alert("Something went wrong call the police");
        }
    });
  });
});

Ajax請求將在Controller中調用此操作,該操作將從數據庫中檢索城市列表return dbContext.CityTable.Where(c => c.StateId == id).ToList()getCititesFromDatabaseByStateId(id) return dbContext.CityTable.Where(c => c.StateId == id).ToList()使用return dbContext.CityTable.Where(c => c.StateId == id).ToList() getCititesFromDatabaseByStateId(id) )然後返回Json對象, success函數將創建一個選項列表並應用它:

public IActionResult getCities(int id)
{
    var cities = new List<City>();
    cities = getCititesFromDatabaseByStateId(id); //call repository
    return Json(citites);
}

ViewModel考慮將IEnumerable<State/City/Zip>IEnumerable<T> )更改為IEnumerable<SelectListItem> 。我可以說你的模型很亂(但是如果你能從數據庫中獲取數據集中在使列表工作第一),那麼考慮以後改進它們。

修復了評論中提到的2個錯誤:

public List<City> getCititesFromDatabaseByStateId(int id)
{
    return db.Citys.Where(c => c.StateId == id).ToList();
}

public ActionResult Create()
{
     var states = new SelectList(db.States.ToList(), "StateId", "Abbr");
     var citys = new SelectList(db.Citys.ToList(), "CityId", "Name");
     var zips = new SelectList(db.Zips.ToList(), "ZipId", "Code");

     var viewModel = new CustomerFormVM
     {
         States = states,
         Citys = citys,
         Zips = zips
     };

     return View(viewModel);
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因