jQuery Autocomplete with multiple fileds in Asp.Net C#


This  article explains jQuery autocomplete with  multiple fields using Asp.Net C#.

Scenario :  Listing business titles for a specific city/state location.

Initially I used AJAX CONTROL TOOLKIT (ACT) but I ran in to many issues and finally decided to use jQuery approach which really saved my time.

You can Download the complete source code from here

Add jQuery assets on your page.

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

jQuery Code for consuming web service.

<script type="text/javascript">
$(function () {
var search = $("#<%=txtSearch.ClientID%>");
var location = $("#<%=txtLocation.ClientID %>");
search.autocomplete({
    source: function (request, response) {
        $.ajax({
            url: '<%=ResolveUrl("~/") %>AutoCompleteService.asmx/GetKeyWords',
            data: "{ 'keyword': '" + search.val() + "', 'location' : '" + location.val() + "'}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                if (data.d != null) {
                    response($.map(data.d, function (item) {
                        return {
                            value: item
                        }
                    }))
                }
            },
            error: function (XMLHttpRequest, textStatus, error) {
                //alert(textStatus);
            }
        });
    },
    minLength: 1
});

location.autocomplete({
    source: function (request, response) {
        $.ajax({
            url: '<%=ResolveUrl("~/") %>AutoCompleteService.asmx/GetLocations',
            data: "{ 'location': '" + location.val() + "'}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataFilter: function (data) { return data; },
            success: function (data) {
                if (data.d != null) {
                    response($.map(data.d, function (item) {
                        return {
                            value: item
                        }
                    }))
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                // alert(textStatus);
            }
        });
    },
    minLength: 1
});

});
</script>

Code-behind for ASMX class (don’t forget to uncomment  System.Web.Script.Services.ScriptService)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Collections;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService {

public AutoCompleteService () {
}

IDictionary<string, string[]> LoadItems()
{
    IDictionary<string, string[]> items = new Dictionary<string, string[]>();

    items.Add("Newyork", new string[]
                                        {
                                            "Applebee's", "Apiary", "Brenda's French Soul Food","TGI Friday's","Cafe Venue"
                                        });

    items.Add("Los Angeles", new string[]
                                        {
                                            "Los 1", "Los 2", "Los 3","TGI Friday's","Cafe Venue"
                                        });

    items.Add("Las Vegas", new string[]
                                        {
                                            "Los 1", "Los 2", "Los 3","TGI Friday's","Cafe Venue"
                                        });

    return items;
}

[WebMethod]
public string[] GetKeyWords(string keyword, string location)
{
    var items = LoadItems();
    if (items != null && items.Count > 0)
    {
        //Get all items for a specific location
        var result = (from item in items
                        where item.Key.Equals(location, StringComparison.OrdinalIgnoreCase)
                        select item.Value)
                    .FirstOrDefault();

        //check whether the items start with the keyword
        return result.Where
                            (
                                o => o.StartsWith(keyword, StringComparison.OrdinalIgnoreCase)
                            ).ToArray<string>();
    }
    return null;
}

[WebMethod]
public string[] GetLocations(string location)
{
    var items = LoadItems();
    if (items != null && items.Count > 0)
    {
        //check whether the items start with the location
        return (from item in items
                        where item.Key.StartsWith(location, StringComparison.OrdinalIgnoreCase)
                        select item.Key).ToArray<string>();

    }
    return null;
}
}

You can Download the complete source code from here

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu

 

Advertisements

jQuery reorder list & saving in to database from Asp.Net C#


I have faced lot of challenges while using Ajax Toolkit control for re-ordering a list and saving to database.. After doing some R&D I’ve  found some nice samples which uses jQuery which is very light weight.The good part of jQuery is we can control the rendering marking.. with CSS and from the backed we don’t need any ViewState or any kind of mechanism..

You can Download the complete source code from here


To begin with reorder stuff add jQuery scripts to your aspx page.

<link rel="stylesheet" type="text/css" href="list-reorder.css" />
<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<script type="text/javascript" src="jquery.disable.text.select.pack.js">
</script>
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript" src="jquery.listreorder.js"></script>

The sample code uses Unordered list and list view control.. Add a List view control in to asp.net page..inside UL markup use class name as “lists“.

Next is adding a attribute to <li> tag which help to identify the exact element you are ordering,  so I am adding attribute name as id and setting value as ItemId which fetching from DB column identity value.

<li id='<%# DataBinder.Eval(Container.DataItem, “ItemId“)%>’>

<ul class="lists">
<asp:ListView ID="lvNews" runat="server">
<LayoutTemplate>
<asp:Panel ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<li id='<%# DataBinder.Eval(Container.DataItem, "ItemId")%>'>
<%# DataBinder.Eval(Container.DataItem, "Title")%></li>
</ItemTemplate>
<ItemSeparatorTemplate>
</ItemSeparatorTemplate>
</asp:ListView>
</ul>

Add following code in codebehind class for binding the data to list view control

using System;
using System.Collections.Generic;

public class News
{

public int ItemId { get; set; }
public string Title { get; set; }

internal static IList<News> GetNews()  //replace this method call with your db logic
{
return new List<News>
{
new News{ItemId=1,Title="News Title 1"},
new News{ItemId=2,Title="News Title 2"},
};
}

internal static void SaveReorderList(List<string> items) //replace this method call with your db logic
{
int order = 1;
string sql = string.Empty;
foreach (string item in items)
{
//replace with your sql statement.
sql = "update news set display_order = " + order + " where news_id = '" + item + "'";
order += 1;
sql = string.Empty;
}
}
}

public partial class jQueryReorder_Net_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindNews();
}
}

private void BindNews()
{
var news = News.GetNews();
lvNews.DataSource = news;
lvNews.DataBind();
}

[System.Web.Services.WebMethod]
public static string SaveReOrder(List<String> items)
{
try
{
News.SaveReorderList(items);
return string.Empty;
}
catch (Exception exp)
{
return exp.ToString();
}
}
}

Finally I am adding jQuery re-order script in to the page.

<script type="text/javascript">
$(document).ready(function() {
var options = {
itemHoverClass: 'itemHover',
dragTargetClass: 'dragTarget',
dropTargetClass: 'dropTarget',
useDefaultDragHandle: true
};

var lists = $('.lists').ListReorder(options);
var items = [];
lists.bind('listorderchanged', function(evt, jqList, listOrder) {
for (var i = 0; i < listOrder.length; i++) {
items[i] = $("ul li:eq(" + i + ")").attr('id');
}
});

$('#btnSave').click(function() {
if (items.length > 0) {
var jsonText = JSON.stringify({ items: items });
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/jQueryReorder.Net/")%>Default.aspx/SaveReOrder',
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { $("#result").html("Reorder items saved successfully"); },
failure: function(msg) { alert(msg); }
});
}
else {
alert("Sorry you have not reorder any items");
}
});
});
</script>

When ever the list order changed the event get fired and loop through the entire list items and sets the attribute id value in to a array which will be converted later to JSON format and pass it to a web method for saving into database. Don’t forget to add method attribute as System.Web.Services.WebMethod in the reorder save method.

You can Download the complete source code from here

Hope this helps and If you have any comments, please feel free to write your feedback.

Thanks
Deepu