Home >Backend Development >C++ >How to Effortlessly Create Cascading Dropdowns in ASP.NET MVC 3 with C#?
With updated technology, implementing cascading drop-down menus in ASP.NET MVC 3 is a piece of cake. This guide will walk you through the process, providing clear solutions using C# and the Razor View Engine.
To create the cascading effect, we first build a model:
<code>public class MyViewModel { public int? Year { get; set; } public int? Month { get; set; } // ... }</code>
Next, we define the corresponding controller:
<code>public class HomeController : Controller { // ... public ActionResult Months(int year) { // 根据所选年份填充月份的逻辑 // ... } }</code>
In the Razor view we use the following code:
<code>@Html.DropDownListFor(x => x.Year, new SelectList(Model.Years, "Value", "Text"), "-- 选择年份 --") @Html.DropDownListFor(x => x.Month, Enumerable.Empty(), "-- 选择月份 --")</code>
We initially populate the "Year" dropdown with a predefined list, while the "Month" dropdown currently remains empty.
JavaScript code implements cascading effect:
<code>$('#Year').change(function () { var year = $(this).val(); if (year) { // AJAX请求,根据所选年份获取月份 $.getJSON('@Url.Action("Months")', { year: year }, function (months) { $('#Month').empty(); $.each(months, function (index, month) { // 使用获取的数据填充“月份”下拉菜单 }); }); } });</code>
When a year is selected, this script will trigger an AJAX call to the controller, retrieve the associated month, and update the Month dropdown accordingly.
With this method, you can easily create cascading drop-down menus in ASP.NET MVC 3, providing a smooth user experience.
The above is the detailed content of How to Effortlessly Create Cascading Dropdowns in ASP.NET MVC 3 with C#?. For more information, please follow other related articles on the PHP Chinese website!