MVC Select2.js使用小结

问题参考:https://www.jb51.net/article/95561.htm

select2.js版本号:3.3.2,不是最新的版本,使用方法和官网上介绍的最新版本有点不太一样。

使用需要引入:select2.min.css和select2.min.js

js:

$(document).ready(function () {
    
    //select2.min.js
    function formatRepo(repo) {
        var markup = "";
        
        markup += "";
        
        markup += "
" + repo.text + "
"; markup += "
" + repo.ISSN + "
"; markup += "
" return markup; } function formatRepoSelection(repo) { return repo.text; } $("#select_CNKI").select2({ placeholder: "请输入期刊名进行知网数据库查询", minimumInputLength: 1, ajax: { // instead of writing the function to execute the request we use Select2's convenient helper url: "/home/myGetCNKI", delay: 250, dataType: 'json', data: function (term) { return { search: term, // search term }; }, results: function (data) { // parse the results into the format expected by Select2. // since we are using custom formatting functions we do not need to alter remote JSON data return { results: data }; }, cache:true }, formatResult: formatRepo, // omitted for brevity, see the source of this page formatSelection: formatRepoSelection, // omitted for brevity, see the source of this page dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results }) })

浏览器发出的Ajax访问需求格式为:/home/mygetCNKI/?search=,可以添加任意多个,改data:选项就是。

HTML:

老版本的只能用在标签里面,新版本的要用在

根据css,网页会显示为:

MVC Select2.js使用小结_第1张图片

Controller:

 '获取数据库中知网的期刊数据
    Class CNKIBookInfo
        Public Property id As Integer
        Public Property text As String
        Public Property ISSN As String
        Public Property imgsrc As String
    End Class
    Function myGetCNKI(ByVal search As String) As JsonResult
        Dim CNKIsearchStr As String = search.Replace(" ", "")
        Dim mybookList As List(Of CNKIBookInfo) = New List(Of CNKIBookInfo)
        If CNKIsearchStr = String.Empty Then
            Return Json(mybookList, JsonRequestBehavior.AllowGet)
            Exit Function
        End If

        Dim CNKIlist = AllinoneDb.Allinone_ISSNInfo.Where(Function(s) s.ISSN_Name.Contains(CNKIsearchStr)).Take(20).ToList
        If IsNothing(CNKIlist) Then
            Return Json(mybookList, JsonRequestBehavior.AllowGet)
            Exit Function
        End If

        For Each item In CNKIlist
            Dim newBook As CNKIBookInfo = New CNKIBookInfo
            newBook.id = item.ISSN_ID
            newBook.text = item.ISSN_Name
            newBook.ISSN = item.ISSN_Code
            newBook.imgsrc = item.ISSN_Cover_Img
            mybookList.Add(newBook)
        Next
        Return Json(mybookList, JsonRequestBehavior.AllowGet)
    End Function

要特别注意:VB语言参数是忽略大小写的,Javascript读data的时候是大小写敏感的。稍微不注意,就会不能正确显示

最终的结果会是这样:

MVC Select2.js使用小结_第2张图片

你可能感兴趣的:(MVC Select2.js使用小结)