The code provided uses the MVVM mode to effectively load the state and cities, but there is still room for improvement.
Simplify state and city selection
Reconstruct the jQuery function, use the method to remove the urban drop -down menu, and then add a new option. Consider the use of
instead of as the first option to allow [Required] to verify. .empty()
val(null)
val(0)
Optimize AJAX calls
<code class="language-javascript">var url = '@Url.Action("GetCities", "Home")'; var cities = $('#CityID'); $('#StateID').change(function() { $.getJSON(url, { id: $(this).val() }, function(response) { cities.empty().append($('<option>').val(null).text('请选择')); $.each(response, function(index, item) { cities.append($('<option>').val(item.Value).text(item.Text)); }); }); });</code>
In order to avoid redundant AJAX calls, a cache mechanism is achieved to store urban data in each state.
Alternative method: initialize urban data
<code class="language-javascript">var cache = {}; $('#StateID').change(function() { var selectedState = $(this).val(); if (cache[selectedState]) { // 从缓存中渲染选项 // ... 使用 cache[selectedState] 渲染城市下拉菜单 ... } else { $.getJSON(url, { id: selectedState }, function(response) { // 添加到缓存 cache[selectedState] = response; // ... 使用 response 渲染城市下拉菜单并添加到缓存 ... }); } });</code>
In the controller:
In the view (script):
Other tips
<code class="language-csharp">model.CityList = db.Cities.Select(d => new { City = d.CountryID, Text = d.CityName, Value = d.Id }).ToList();</code>
<code class="language-javascript">// 将所有城市赋值给JavaScript数组 var allCities = JSON.parse('@Html.Raw(Json.Encode(Model.CityList))'); $('#StateID').change(function() { var selectedState = $(this).val(); var cities = $.grep(allCities, function(item, index) { return item.CountryID == selectedState; }); // 基于cities的值构建选项 // ... 使用 cities 数组渲染城市下拉菜单 ... });</code>
Use the built -in auxiliary method (@url.action,@html.raw) to make the code concise and avoid hard coding.
The above is the detailed content of How Can I Optimize Loading Two Dependent Dropdowns in MVC?. For more information, please follow other related articles on the PHP Chinese website!