select2-4.0.3
案例 想深入了解的可以看看https://select2.org/
//控制器
/// <summary>
/// select获取角色
/// </summary>
/// <param name="keyWord">文本框输入的内容</param>
/// <param name="pageSize">每页几条数据</param>
/// <param name="pageIndex">当前页</param>
/// <returns></returns>
public ActionResult GetRoleJson(string keyWord, int pageSize, int pageIndex = 1)
{
List<RoleDb> roleList = RoleBll.Instance.GetRoleListAllInCache();//获取List<RoleDb>的集合
if (!string.IsNullOrEmpty(keyWord))//判断select2文本框中是否输入内容
{
roleList = roleList.Where(c => c.role_name.Contains(keyWord)).ToList();//lamda表达式进行查询
}
roleList = (from r in roleList select r).Take(pageSize * pageIndex).Skip(pageSize * (pageIndex - 1)).ToList();//分页(可选)
//封装json对象
JObject rss = new JObject(
new JProperty("total", roleList.Count),
new JProperty("results",
new JArray(
from r in roleList
select new JObject(
new JProperty("id", r.role_id)
, new JProperty("text", r.role_name)
)
)
)
);
return Content(rss.ToString());
}
//视图
<span class="li_con" >
<select id='role_id' style="width:60%;text-align:right;padding-left:5px" multiple='multiple'>
@foreach (var item in roleList)
{
@*<option value='@item[1]' selected='selected'>@item[0]</option>如果有需求可以直接写open*@
}
</select>
<input type='hidden' name='role_names' id='role_names_hid' value='' />
<input type='hidden' name='role_ids' id='role_id_hid' value='' />
@Html.ValidationMessageFor(c => c.role_ids)
<script>
$(document).ready(function () {
$('#role_id').select2({
language: 'zh-CN',
quietMillis: 1000,
minimumInputLength: 0,
maximumInputLength: 10,
ajax: {
url: '/RoleManager/GetRoleJson',//控制器名
dataType: 'json',//返回值类型json
delay: 1000,
data: function (params) { return { keyWord: params.term, pageIndex: params.page || 1, pageSize: 7 }; },
processResults: function (data, params) { return { results: data.results, pagination: { more: data.results.length > 0 } }; },
cache: true
}
}).on('change', function () {//改变事件时触发
$('#role_id_hid').val($('#role_id').val());//把值存到隐藏域中
$('#role_names_hid').val($("#role_id").find("option:selected").text());//把值存到隐藏域中
});
});
</script>
</span>