Home >Backend Development >C++ >How to Implement Cascading Dropdowns in ASP.NET MVC 3 Using C#?

How to Implement Cascading Dropdowns in ASP.NET MVC 3 Using C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-11 15:36:42665browse

How to Implement Cascading Dropdowns in ASP.NET MVC 3 Using C#?

Implementing Cascading Dropdown Menu in ASP.NET MVC 3 using C#: Complete Guide

When creating cascading dropdown menus in ASP.NET MVC 3, it can be overwhelming to come across outdated solutions or commands that are deprecated in that version. This guide provides a step-by-step method for creating cascading drop-down menus using C#, ensuring compatibility with MVC 3.

Model Design

The foundation of any MVC application is the model. In this example, we will create a model called MyViewModel to represent the data of the drop-down menu:

<code class="language-csharp">public class MyViewModel
{
    public int? Year { get; set; }
    public int? Month { get; set; }

    // 第一个下拉菜单的年份选项集合
    public IEnumerable Years
    {
        get
        {
            return Enumerable.Range(2000, 12).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = x.ToString()
            });
        }
    }
}</code>

Build Controller

Controllers act as intermediaries between models and views. Here we define an action to populate the first dropdown with the year and another action to provide the month based on the selected year:

<code class="language-csharp">public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    public ActionResult Months(int year)
    {
        if (year == 2011)
        {
            return Json(
                Enumerable.Range(1, 3).Select(x => new { value = x, text = x }),
                JsonRequestBehavior.AllowGet
            );
        }
        return Json(
            Enumerable.Range(1, 12).Select(x => new { value = x, text = x }),
            JsonRequestBehavior.AllowGet
        );
    }
}</code>

Create View

View displays the user interface of the application. In this example, we use Razor syntax to define two drop-down menus: one for selecting the year and another for selecting the month:

<code class="language-csharp">@model AppName.Models.MyViewModel

@Html.DropDownListFor(
    x => x.Year,
    new SelectList(Model.Years, "Value", "Text"),
    "-- 选择年份 --"
)

@Html.DropDownListFor(
    x => x.Month,
    Enumerable.Empty(),
    "-- 选择月份 --"
)

<script>
    $('#Year').change(function () {
        var selectedYear = $(this).val();
        if (selectedYear != null && selectedYear != '') {
            $.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) {
                var monthsSelect = $('#Month');
                monthsSelect.empty();
                $.each(months, function (index, month) {
                    monthsSelect.append($('<option>', {
                        value: month.value,
                        text: month.text
                    }));
                });
            });
        }
    });
</script></code>

This JavaScript code triggers an AJAX call to the controller action Months after changing the selected year. It then uses the returned JSON data to populate the second dropdown menu with the appropriate month.

Conclusion

This approach provides a clear and concise way to implement cascading drop-down menus in ASP.NET MVC 3 using C#. By following these steps, you can easily create a user-friendly and responsive interface for managing hierarchical data.

The above is the detailed content of How to Implement Cascading Dropdowns in ASP.NET MVC 3 Using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn