【问题标题】:How search using dropdownList is ASP.NET Core MVCASP.NET Core MVC 如何使用 dropdownList 进行搜索
【发布时间】:2019-07-07 07:51:31
【问题描述】:

我有一张表格,我正在尝试在其中进行搜索,它适用于所有内容,除了使用 dropdownList 添加的表格。

在数据库中它们被保存为 tinyint,所以当我按数字搜索时,它可以工作,但我想按单词搜索。

例如我使用这段代码来初始化它们:

public enum Education : Int16
{
       PHD = 1,
}

当我搜索“1”时,它会显示其中包含 PHD 的结果,但是当我搜索“PHD”时,什么都没有显示。

我正在使用 ADO.NET 进行 CRUD 操作

这是我在控制器中使用的方法的代码:

string connectionString = Configuration["ConnectionStrings:WebApplication7ContextConnection"];
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            //SqlDataReader
            connection.Open();
            string email = User.Identity.Name;
            SqlCommand command = new SqlCommand(email, connection);

            if(searchString == null)
            {
            string sql = "Select * From Teacher Where Email = '" + email + "' ORDER BY AddedOn DESC";
            SqlCommand command2 = new SqlCommand(sql, connection);

            using (SqlDataReader dataReader = command2.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    ContactUsMessage teacher = new ContactUsMessage();
                    teacher.Id = Convert.ToInt32(dataReader["Id"]);
                    teacher.Name = Convert.ToString(dataReader["Name"]);
                    teacher.Email = Convert.ToString(dataReader["Email"]);
                    teacher.Phone = Convert.ToString(dataReader["Phone"]);
                    teacher.education = (Education)Convert.ToInt16(dataReader["Education"]);
                    teacher.Message = Convert.ToString(dataReader["Message"]);
                    teacher.AddedOn = Convert.ToDateTime(dataReader["AddedOn"]);

                    teacherList.Add(teacher);
                }
            }
            }
            else
            {
                string sql = "Select * From Teacher Where Email = '" + email + "' AND education = '"+searchString+"' AND Message LIKE '%"+searchString+"%' OR Name LIKE '%" + searchString + "%' OR Phone LIKE '%" + searchString + "%'  ORDER BY AddedOn DESC";
                SqlCommand command2 = new SqlCommand(sql, connection);

                using (SqlDataReader dataReader = command2.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        ContactUsMessage teacher = new ContactUsMessage();
                        teacher.Id = Convert.ToInt32(dataReader["Id"]);
                        teacher.Name = Convert.ToString(dataReader["Name"]);
                        teacher.Email = Convert.ToString(dataReader["Email"]);
                        teacher.Phone = Convert.ToString(dataReader["Phone"]);
                        teacher.education = (Education)Convert.ToInt16(dataReader["Education"]);
                        teacher.Message = Convert.ToString(dataReader["Message"]);
                        teacher.AddedOn = Convert.ToDateTime(dataReader["AddedOn"]);

                        teacherList.Add(teacher);
                    }
                }

            }


            connection.Close();
        }
        return View(teacherList);

【问题讨论】:

标签: c# asp.net asp.net-core


【解决方案1】:

您可以使用 Select2 下拉列表(自动完成 + 组合框),如下所示:

查看:

@Html.DropDownListFor(m => m.StudentId, Enumerable.Empty<SelectListItem>(), "Please select", new { @class = "", /* @Value = 1*/ })

$(document).ready(function () {

    var student = $("#StudentId");

    //for Select2 Options: https://select2.github.io/options.html
    student.select2({
            language: "tr",//don't forget to add language script (select2/js/i18n/tr.js) 
                //dropdownParent: $('#yourModal'), //In order to make search box enabled when using Select2 on Bootstrap modal (otherwise remove "tabindex" from modal properties).
        //minimumResultsForSearch: Infinity, //permanently hide the search box
        minimumInputLength: 0, //for listing all records > set 0
        maximumInputLength: 20, //only allow terms up to 20 characters long         
        multiple: false,
        placeholder: "Seçiniz",
        allowClear: true,
        tags: false, //prevent free text entry
        width: "100%",

        ajax: {
            url: '/Grade/StudentLookup',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    query: params.term, //search term
                    page: params.page
                };
            },
            processResults: function (data, page) {
                var newData = [];
                $.each(data, function (index, item) {
                    newData.push({
                            //id part present in data 
                            id: item.Id,     
                            //string to be displayed
                            text: item.Name + " " + item.Surname
                    });
                });
                return { results: newData };
            },
            cache: true
        },
        escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
        //templateResult: formatRepo, // omitted for brevity, see the source of this page
        //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
    });


    //You can simply listen to the select2:select event to get the selected item
    student.on('select2:select', onSelect)

    function onSelect(evt) {
        console.log($(this).val());
    }

        //Event example for close event
        student.on('select2:close', onClose)

        function onClose(evt) {
            console.log('Closed…');
        } 
});

控制器:

public ActionResult Create()
{ 
    return PartialView("_Create"); //DO NOT fill the dropdownlist in this method
}


public ActionResult StudentLookup(string query)
{
    var students = repository.Students.Select(m => new StudentViewModel
    {
        Id = m.Id,
        Name = m.Name,
        Surname = m.Surname
        //FullName = m.Name + " " + m.Surname //Sending "Name" and "Surname" in one parameter    causes "The specified type member 'FullName' is not supported in LINQ to Entities" error!
    })
    //if "query" is null, get all records
    .Where(m => string.IsNullOrEmpty(query) || m.Name.StartsWith(query)) 
    .OrderBy(m => m.Name);
    return Json(students, JsonRequestBehavior.AllowGet);
}

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 2015-12-23
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2016-02-25
    相关资源
    最近更新 更多