使用 Jquery 建立可搜尋的下拉選擇框 - 在 C MVC 中選擇 select2
此示例將演示 MVC 中的可搜尋選擇框。當使用者鍵入新字元時,它使用 Ajax 從資料庫獲取所有記錄。我將考慮 Country 和它的 City 示例來說明 Searchable 下拉框的功能。程式碼背後是帶 MVC 的 C#,但它易於掌握整個概念。
首先,我以步進方式建立了基本背景。最後一步是執行此程式碼的 Select2 jqery 方法。
第 1 步: 在剃刀中宣告 DropDownListFor 控制元件。它在 HTML 標記中建立選擇框。
隱藏變數 ajaxUrlGetAutoCompleteSearchSuggestion
將由 Jquery 的 Ajax 呼叫 - select2 庫方法使用。
隱藏變數值欄位還包含剃刀庫方法 url.action。它有兩個引數。第一個引數,GetAutoCompleteSearchSuggestion 是 C#方法,它是伺服器端的入口點,用於 Ajax 呼叫以獲取記錄。第二個引數是控制器名稱 Country
。
<h2>
<label>@Html.LabelFor(m => m.ddlCountry)</label>
@Html.DropDownListFor(m => m.ddlCountry, Model.Station, new { @class = "select2Style" })
</h2>
<input type="hidden" id="ajaxUrlGetAutoCompleteSearchSuggestion" value='@Url.Action("GetAutoCompleteSearchSuggestion", "Country")' />
第 2 步: 這些是可用於選擇框的預定義 CSS 類。你可以使用這些類自定義控制元件。此外,你可以為控制元件新增自己的 css 類。
/* Input field */
.select2-selection__rendered { font-size:medium; font-weight:normal; }
/* Around the search field */
.select2-search { font-size:small; font-weight:normal; }
/* Search field */
.select2-search input { font-size:medium; font-weight:normal; }
/* Each result */
.select2-results {
font-family: Arial, Helvetica, sans-serif;
font-size: medium;
font-weight:normal;
}
/* Higlighted (hover) result */
.select2-results__option--highlighted { font-size:medium; font-weight:normal; }
/* Selected option */
.select2-results__option[aria-selected=true] {
background: #3ea211;
font-family: Arial, Helvetica, sans-serif;
font-size:medium;
font-weight:normal;
}
/* My css class*/
.select2Style {
width:200px;
}
第 3 步: 建立模型。請注意,相同的變數名稱在剃刀宣告中。
[Display(Name = "Country:")]
public string ddlCountry { get; set; }
public IEnumerable<SelectListItem> Country { get; set; }
步驟 4: 建立 Country
Controller 和 C#方法,每當使用者在可搜尋的下拉選單文字框中輸入文字時,該方法將由 jquery ajax 方法呼叫。
public ActionResult GetAutoCompleteSearchSuggestion(CountryQuery queryParameters)
{
string ErrorMessage = "success";
Dictionary<double, string> suggestions = new Dictionary<double, string>();
try
{
suggestions = GetCountryList( queryParameters.query);
}
catch (Exception Ex)
{
ErrorMessage = Ex.Message;
return Json(ErrorMessage);
}
return Json(suggestions.Select(c => new { Name = c.Value, ID = c.Key }).ToList(),
JsonRequestBehavior.AllowGet);
}
步驟 5: 設定資料庫查詢和操作以獲取記錄。它獲得了國家列表。請注意 db 查詢,它會影響獲取和顯示下拉項的方式。你必須自定義查詢以根據你的要求獲取結果。
public Dictionary<string, string> GetCountryList(string filterId)
{
Dictionary<string, string> ddlcountryDictionary = new Dictionary<string, string>();
OracleDataReader reader = null;
OracleConnection oraConnection = new OracleConnection(oracleConnStr);
string firstItem = string.Empty;
try
{
oraConnection.Open();
string ddlQuery = "SELECT CountryId, countryName FROM tblCountry WHERE UPPER(countryName) LIKE UPPER ('"+filterId+"%') ORDER BY 2 ASC";
oraCommand = new OracleCommand(ddlQuery, oraConnection);
reader = oraCommand.ExecuteReader();
string countryValue = "Select Item";
string countryId = -1;
if (reader.HasRows)
{
while (reader.Read())
{
countryId = reader[0].ToString();
countryValue = reader[1].ToString();
ddlcountryDictionary.Add(countryId, countryValue);
}
}
}
catch (Exception ex)
{
throw new Exception("No Country name Exists.");
}
finally
{
reader.Dispose();
oraCommand.Dispose();
oraConnection.Close();
}
return ddlcountryDictionary;
}
第 6 步: jQuery 函式會列出國名開始與使用者輸入的文字,如果使用者選擇 是 ,那麼所有國家與名字開始 一 將陸續上市和明年,如果使用者鍵入 N
則國名未開始 an
將被過濾掉。
$("#ddlCountry").select2({
ajax: {
url: $("#ajaxUrlGetAutoCompleteSearchSuggestion").val(),
data: function (params) {
var queryParameters = {
//restrictedCountry: $("#resCountry").val(), // pass your own parameter
query: params.term, // search term like "a" then "an"
page: params.page
};
return queryParameters;
},
dataType: "json",
cache: true,
delay: 250,
//type: 'POST',
contentType: "application/json; charset=utf-8",
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data, function (val, item) {
return { id: val.ID, text: val.Name };
}),
// if more then 30 items in dropdown, remaining set of items will be show on numbered page link in dropdown control.
pagination: { more: (params.page * 30) < data.length }
};
}
},
minimumInputLength: 1 // Minimum length of input in search box before ajax call triggers
});
請在此站點檢視 Select2 的各種示例