The strategy of loading the state -to -drop -down list of the state of the state and the city
The method of loading the state -drop -down list directly when loading on the page is inefficient. This article will introduce more efficient and best practices.
Recommended method:
<.> 1. Use the view model:
Create a view model, including Stateid, Cityid, Statelist, and CityList properties. This helps package data and provides strong types.<.> 2. Use non -invasive javascript:
Avoid using the Inner Union JavaScript in the mark. Instead, the non -invasive JavaScript is used to separate HTML and behavior.
Drop -down list Modification:
Cache optimization:
<code class="language-html">@Html.DropDownList(m => m.StateID, States, "选择州") //移除onchange属性 @Html.DropDownListFor(m => m.CityID, Cities, "选择城市") //保留默认ID</code>
Ajax replacement method:
<code class="language-javascript">const url = '@Url.Action("GetCities", "Home")'; // 使用助手方法 const citiesDropdown = $('#CityID'); // 缓存元素 $('#StateID').change(function () { $.getJSON(url, { id: $(this).val() }, function (response) { // 清空并添加默认(null)选项 citiesDropdown.empty().append($('<option></option>').val('').text('请选择')); $.each(response, function (index, item) { citiesDropdown.append($('<option></option>').val(item.Value).text(item.Text)); }); }); });</code>
If the number of states and cities is limited, all cities can be passed to the view and assigned them to the JavaScript array. However, this may lead to a long time of the initial loading. In the controller:
<code class="language-javascript">const cache = {}; $('#StateID').change(function () { const selectedState = $(this).val(); if (cache[selectedState]) { // 从缓存中渲染选项 // ... 使用cache[selectedState]渲染城市下拉列表 } else { $.getJSON(url, { id: selectedState }, function (response) { // 添加到缓存 cache[selectedState] = response; // ... 使用response渲染城市下拉列表 }); } });</code>
The above is the detailed content of How Can I Improve the Efficiency of Loading Dropdown Lists for States and Cities?. For more information, please follow other related articles on the PHP Chinese website!