[英]asp.net mvc core select2 dropdown autopopulate ajax call
我有一個視圖,我正在嘗試實現自動填充文本框/下拉字段。 我正在使用我查詢的列表。
我正在關注這個例子http://www.dotnetqueries.com/Article/159/how-to-implement-select2-with-ajax-and-json-in-asp-net-mvc ,斷點甚至沒有命中我的 controller 中的方法。 那么我設置它的方式或在 controller 中調用操作結果方法的方式是否有問題。
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using TestSelect2.Models;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
namespace TestSelect2.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[Microsoft.AspNetCore.Mvc.HttpPost]
[Microsoft.AspNetCore.Mvc.Route("/home/account-list")]
public Microsoft.AspNetCore.Mvc.ActionResult GetAccounts(string q)
{
List<Account> accounts = new List<Account>();
// Add parts to the list.
accounts.Add(new Account() { Id = 1, AccountNumber = "MVP1" });
accounts.Add(new Account() { Id = 1, AccountNumber = "MVP11" });
accounts.Add(new Account() { Id = 1, AccountNumber = "ABC2" });
accounts.Add(new Account() { Id = 1, AccountNumber = "ABC3" });
accounts.Add(new Account() { Id = 1, AccountNumber = "XYZ3" });
accounts.Add(new Account() { Id = 1, AccountNumber = "XYZ4" });
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
accounts = accounts.Where(x => x.AccountNumber.ToLower().StartsWith(q.ToLower())).ToList();
}
return Json(new { items = accounts }, JsonRequestBehavior.AllowGet);
}
}
}
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Select2 DEMO</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script>
$(document).ready(function () {
$(".accountSelect").select2({
ajax: {
url: '/home/account-list',
width: 'resolve',
data: function (params) {
return {
q: params.term// search term
};
},
processResults: function (data) {
return {
results: data.items
};
},
minimumInputLength: 2,
width: 'resolve'
}
});
});
</script>
<style>
body {
margin: auto;
width: 600px;
padding: 50px;
}
.accountSelect {
width: 400px;
}
</style>
</head>
<body>
<form method="post">
<select class="accountSelect"></select>
</form>
</body>
</html>
刪除GetAccounts
操作上的[HttpPost]
屬性。 由於 ajax 發出獲取請求。您遵循的教程適用於asp.net
而不是asp.net core
,因此沒有JsonRequestBehavior
。
注意:select2model 必須帶有id
和text
兩個屬性,否則無法識別。 更改您的Account
model 如下所示:
public class Account
{
public int Id { get; set; }
public string Text { get; set; }
}
和 controller 動作,確保 id 不能相同。
[Route("/home/account-list")]
public IActionResult GetAccounts(string q)
{
List<Account> accounts = new List<Account>();
// Add parts to the list.
accounts.Add(new Account() { Id = 1, Text = "MVP1" });
accounts.Add(new Account() { Id = 2, Text = "MVP11" });
accounts.Add(new Account() { Id = 3, Text = "ABC2" });
accounts.Add(new Account() { Id = 4, Text = "ABC3" });
accounts.Add(new Account() { Id = 5, Text = "XYZ3" });
accounts.Add(new Account() { Id = 6, Text = "XYZ4" });
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
accounts = accounts.Where(x => x.Text.ToLower().StartsWith(q.ToLower())).ToList();
}
return Json(new { items = accounts });
}
視圖和腳本:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Select2 DEMO</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script>
$(document).ready(function () {
$(".accountSelect").select2({
minimumInputLength: 2,
ajax: {
url: '/home/account-list',
data: function (params) {
return {
q: params.term// search term
};
},
processResults: function (data) {
return {
results: data.items
}
},
}
});
});
</script>
<style>
body {
margin: auto;
width: 600px;
padding: 50px;
}
.accountSelect {
width: 400px;
}
</style>
</head>
<body>
<form method="post">
<select class="accountSelect"></select>
</form>
</body>
</html>
結果:
您可以嘗試如下:
//1. Action Method Which Returns the data.
public ActionResult GetSelect2Data(string query)
{
//In Realtime This should come from the Database
List<DropDownItem> collection = new List<DropDownItem>() {
new DropDownItem(){ Value = 1, Text = "Switzerland"},
new DropDownItem(){ Value = 2, Text = "Canada"},
new DropDownItem(){ Value = 3, Text = "Japan"},
new DropDownItem(){ Value = 4, Text = "Germany"},
new DropDownItem(){ Value = 5, Text = "Australia"},
new DropDownItem(){ Value = 6, Text = "United Kingdom"},
new DropDownItem(){ Value = 7, Text = "United States"},
new DropDownItem(){ Value = 8, Text = "Sweden"},
new DropDownItem(){ Value = 9, Text = "India"},
new DropDownItem(){ Value = 10, Text = "Russia"},
};
var searchResult = from c in collection
where c.Text.Contains(query,
StringComparison.CurrentCultureIgnoreCase)
select c;
return Json(searchResult.ToList());
}
///2. JS Method which binds any HTML Select as Select2 or Smart Select.
///In the User Interface (.cshtml file)You may define a framework JS Function as which could be used anywhere
function registerSelect2(dropDownSelector, ajaxUrl) {
$(dropDownSelector).select2({
ajax: {
url: ajaxUrl,
dataType: 'json',
delay: 10,
type: 'GET',
data: function (params) {
return {
query: params.term, // search term
};
}
, processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.value,
text: item.text,
};
})
};
},
cache: true,
},
minimumInputLength: 3,
allowHtml: true,
allowClear: true
});
}
//3. Invoke the JS Function to make any particular Select a Select2.
$(function () {
//Just you need to pass the Selector of your control and the Ajax Url from which data has to be loaded
registerSelect2("#ddlSelect2", "/user/GetSelect2Data");
});
//This is the Simple Select which's made a Select2 Control. Paste it somewhere in the UI
<select id="ddlSelect2"></select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.