[RESOLVED]jquery autocomplete not work

hi there,

i use the bellow codes but it not work?!

in default.aspx

<script src="js/jquery-2.0.3.min.js" type="text/javascript"></script>
    <script src="js/jquery-ui.js" type="text/javascript"></script>
    <link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript">

    $(function () {
        $('#<%=txtSearch.ClientID%>').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "default.aspx/GetBook",
                    data: "{'pre' :'" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {

                            return {
                                Name: item.Name,
                                Cover: item.Picture,
                                json: item
                            }
                        }))
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            focus: function (event, ui) {
                // this is for when focus of autocomplete item 
                $('#<%=txtSearch.ClientID%>').val(ui.item.Name);
                return false;
            },
            select: function (event, ui) {
                // this is for when select autocomplete item
                $('#<%=txtSearch.ClientID%>').val(ui.item.Name);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
            // here return item for autocomplete text box, Here is the place 
            // where we can modify data as we want to show as autocomplete item
            return $("<li>")
             .append("<a style='padding-left:40px; background-image:url(/Uploads/booksPic/" + item.Picture + ");" +
             "background-repeat:no-repeat;background-position:left center;' >" + item.Name + "</a>").appendTo(ul);
        };
    });

</script>


 <asp:TextBox ID="txtSearch" size="40" placeholder="جستجو..." runat="server"></asp:TextBox>

and default.aspx.cs

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static List<Book> GetBook(string pre)
    {
        List<Book> allBooks = new List<Book>();
        using (mydbEntities context = new mydbEntities())
        {
            allBooks = context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).ToList();

        }
        return allBooks;
    }

Your code looks correct, you need to check if you have no scripting errors in runtime. 

Open the page in browser, open F12-developer tools and see Console.

smirnov

Your code looks correct, you need to check if you have no scripting errors in runtime. 

Open the page in browser, open F12-developer tools and see Console.

hi smirnov, i got this message

Based on the error that you are receiving, which is simply a 500 server error that indicates something went wrong in your server-side code, you might try using the following and ensuring that your query is being executed within your using statement :

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
        using (mydbEntities context = new mydbEntities())
        {
            return context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).ToList();
        }
}

I still get the error,

Is it because the response size? because the book table have  20 fields but i just need Book.Id,Book.Name,Book.Picture

How can I return just that three fields?

MostafaTaghipour

How can I return just that three fields?

you can return just three field using select() on the previous post like

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
        using (mydbEntities context = new mydbEntities())
        {
            return context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).select(a=>new{

              a.Id,
              a.Name,
              a.Picture
            }).ToList();
        }
}

You need to test if your method returns expected result.

Just copy your code somewhere in a test method and run

List<Book> allBooks = new List<Book>();
using (mydbEntities context = new mydbEntities())
{
allBooks = context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).ToList();

}
foreach(Book b in allBooks)
Response.Write(b.Name);

to test your web method you could also try to change it to return just one test record as

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
List<Book> allBooks = new List<Book>();
allBooks.Add(new Book() { Name = "Test", Picture = "Test" });
return allBooks;
}

Hi Mostafa,

As your error said ,  I suggest you try to test as below method , and know how many values was returned by your method .

         using (mydbEntities context = new mydbEntities())

        {

            allBooks = context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).ToList();

        }

Accroding to your result , please change your behind code as below if the value’s length didn’t match your code ,

                using (mydbEntities context = new mydbEntities())

        {

            return context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).select(a=>new{

              a.Id,

              a.Name,

              a.Picture

            }).ToList();

        }

Best regards,

Aswecan

arahaman.ashik

you can return just three field using select() on the previous post like
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
        using (mydbEntities context = new mydbEntities())
        {
            return context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).select(a=>new{

              a.Id,
              a.Name,
              a.Picture
            }).ToList();
        }
}

i got this error

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<mydbModel.Book>'	

MostafaTaghipour

arahaman.ashik

you can return just three field using select() on the previous post like
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
        using (mydbEntities context = new mydbEntities())
        {
            return context.Books.Where(a => a.Name.StartsWith(pre)).OrderBy(a => a.Name).select(a=>new{

              a.Id,
              a.Name,
              a.Picture
            }).ToList();
        }
}

i got this error

Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<mydbModel.Book>'	

You would need to explicitly cast it as a Book instead of an anonymous object :

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
        using (mydbEntities context = new mydbEntities())
        {
            return context.Books.Where(a => a.Name.StartsWith(pre))
                                .OrderBy(a => a.Name)
                                .AsEnumerable()
                                .Select(a => new Book(){ Id = a.Id, Name = a.Name, Picture = a.Picture })
                                .ToList();
        }
}

Although it would seem like you should just be able to use :

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Book> GetBook(string pre)
{
        using (mydbEntities context = new mydbEntities())
        {
            return context.Books.Where(a => a.Name.StartsWith(pre))
                                .OrderBy(a => a.Name)
                                .ToList();
        }
}

Leave a Reply