C# を使用して ASP.NET MVC 3 でカスケード ドロップダウンを構築する
Web アプリケーションの開発では、多くの場合、あるドロップダウンのオプションが別のドロップダウンの選択に依存する、カスケード ドロップダウン リストの実装が必要になります。このチュートリアルでは、ASP.NET MVC 3 と C# を使用してこの機能を実現する方法を説明します。
データ モデル:
まず、年と月を含むデータを表すモデルを定義します。
<code class="language-csharp">public class MyViewModel { public int? Year { get; set; } public int? Month { get; set; } // ... other properties }</code>
コントローラーのアクション:
コントローラーは、データの取得とビューへの配信を管理します。
<code class="language-csharp">public class HomeController : Controller { // ... other actions public ActionResult Months(int year) { // ... logic to retrieve months based on the selected year } }</code>
実装の表示:
Razor ビューは、ヘルパー メソッドを使用してドロップダウン リストを生成し、動的更新のために JavaScript を組み込みます。
<code class="language-html">@Html.DropDownListFor( model => model.Year, new SelectList(Model.Years, "Value", "Text"), "-- Select Year --" ) @Html.DropDownListFor( model => model.Month, Enumerable.Empty<SelectListItem>(), "-- Select Month --" ) <script> $('#Year').change(function () { // ... AJAX call to update the month dropdown }); </script></code>
クライアントサイド JavaScript:
jQuery は、年のドロップダウン変更イベントによってトリガーされた AJAX リクエストを処理するために使用されます。 リクエストは、コントローラーの Months
アクションから適切な月を取得し、それに応じて月のドロップダウンを設定します。
このアプローチにより、ASP.NET MVC 3 でカスケード ドロップダウンをシームレスに作成でき、ユーザー エクスペリエンスが向上します。
以上がC# を使用して ASP.NET MVC 3 でカスケード ドロップダウンを作成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。