2

我正在开发一个应用程序,在该应用程序中,我需要为用户提供搜索选项,例如如果用户输入“科学”,搜索功能应该获得具有名称科学的课程,或者如果在他们的描述科学中出现类似单词,我的意思是说如果用户输入一半单词查询应该通过匹配字符序列来获得完整的单词,但我不知道如何实现这一点,我在我的应用程序中使用实体框架。

我还需要从多个表中搜索一件事。

提前致谢。

4

1 回答 1

1

我认为你想实现自动完成,如果是这样,那么下面的代码将解决你的问题:

代码文件:

 [WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetPatientLastName(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        string connectionstring = CCMMUtility.GetCacheForWholeApplication();
        conn.ConnectionString = connectionstring;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select distinct top(10) PatientLastname from tblMessage where  " +
            "PatientLastname  like '%'+ @SearchText + '%' order by PatientLastname";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}", sdr["PatientLastname"]));
                }
            }
            conn.Close();
        }
        return customers.ToArray();
    }
}

jQuery代码:

 $(document).ready(function () {
        $('[ID$=txtPatientLastname]').live('keyup.autocomplete', function () {

            $(this).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '<%=ResolveUrl("~/Resources/WebService.asmx/GetPatientLastName") %>',
                        data: "{ 'prefix': '" + request.term + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('-')[0],
                                    val: item.split('-')[1]
                                }
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                },
                minLength: 1
            });
        });
});

希望这将满足您的要求。

于 2013-01-04T12:02:53.120 回答