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

 

Asp.Net 3.5 Ajax Modal Popup Extender with User Control Event Bubbling


I had a requirement to implement login control in a pop up window using Ajax Modal Popup extender. In this article I am discussing how to implement Usercontrol event bubbling (ie subscribe the user control event  in the parent page)  and the AjaxModal popup extender.

You can download the entire article from here

For more information about Ajax Model Popup Extender please visit http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/ModalPopup/ModalPopup.aspx

If you find the Ajax Modal Popup code library useful, please consider donating



Scenario

Logged In users only can post the comment..
Login control is implemented in ASCX file.
Once the user logged in Successfully the user control event get fired in the Login Control ASCX page which is subscribed in the parent ASPX page.

Following are the screen shots for login control page and aspx page.

For more information about the user control event bubbling please visit the following links

http://asp.net-tutorials.com/user-controls/events/

http://codebetter.com/blogs/brendan.tompkins/archive/2004/10/06/Easily-Raise-Events-From-ASP.NET-ASCX-User-Controls.aspx

http://odetocode.com/code/94.aspx

Create a new ASCX  file called PopupLoginControl.ascx and copy paste the following markup tags.

<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”ajaxtoolkit” %>

<asp:Button ID=”btnShowPopup” runat=”server” Style=”display: none” />

<ajaxtoolkit:ModalPopupExtender BackgroundCssClass=”modalBackground”
CancelControlID=”btnClose” runat=”server” PopupControlID=”Panel1″ ID=”ModalPopupExtender1″
TargetControlID=”btnShowPopup” />

<asp:Panel ID=”Panel1″ runat=”server” CssClass=”modalPopup” DefaultButton=”btnOk”>
<table width=”100%” border=”0″ cellpadding=”2″ cellspacing=”5″>
<tr>
<td style=”width:35%;padding-top:50px;”>
</td>
<td>
<asp:Label id=”labMsg” runat=”server” />
</td>
</tr>
<tr>
<td align=”right” valign=”middle”>
<strong>Email Id :</strong>
</td>
<td>
&nbsp;<asp:TextBox ID=”txtLogin” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td align=”right” valign=”middle”>
<strong>Password :</strong>
</td>
<td>
&nbsp;<asp:TextBox ID=”txtPassword” runat=”server” TextMode=”Password”></asp:TextBox>
</td>
</tr>
<tr>
<td>

</td>
<td>
<asp:Button ID=”btnOk” OnClick=”Login” runat=”server” Text=”Sign In” />
<asp:Button ID=”btnClose” runat=”server” Text=”Cancel” />

</td>
</tr>
</table>
</asp:Panel>

PopupLoginControl.ascx.Cs

 public event EventHandler LoginStatus;
 bool status;

 public Boolean IsLogin
 {
 get { return status; }
 }
 protected void Page_Load(object sender, EventArgs e)
 {

 }
 protected void Login(object sender, EventArgs e)
 {
 labMsg.Text = string.Empty;

 ModalPopupExtender1.Show(); //show pop up window

 if (LoginStatus != null)
 {
 if (txtLogin.Text.Equals("admin") && txtPassword.Text.Equals("admin"))
 {
 status = true;

 LoginStatus(this, EventArgs.Empty); //event get fired here.

 ModalPopupExtender1.Hide(); //hide pop up window once the user logged in successfully.
 }
 else
 {
 labMsg.Text = "<font color=red>Sorry user name and password could not find</font>";
 }
 }
 }
 public void EnableModelDialog(bool visibility)
 {
 if (visibility)
 {
 ModalPopupExtender1.Show();
 }
 else
 {
 ModalPopupExtender1.Hide();
 }
 }

LoginTest.aspx page(Markup)

<%@ Register Src=”PopupLoginControl.ascx” TagName=”PopupLoginControl” TagPrefix=”uc1″ %>

<style type=”text/css”>
.modalBackground
{
background-color: Gray;
filter: alpha(opacity=70);
opacity: 0.7;
}
.modalPopup
{
background-color: White;
height: 250px;
width:500px;
text-align:left;
}
</style>

<form id=”form1″ runat=”server”>

<asp:ScriptManager ID=”Scriptmanager1″ runat=”server” />

<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>

<ContentTemplate>

<asp:LinkButton ID=”lnkWriteMessage” runat=”server” OnClick=”ShowMessage”>Write Comments</asp:LinkButton>

<uc1:PopupLoginControl ID=”PopupLoginControl1″  OnLoginStatus=”PopupLoginCntl_Completed”
Visible=”false” runat=”server” />

<asp:Panel ID=”divComments” Visible=”false” runat=”server”>

<table width=”50%”>
<tr>
<td>
<textarea id=”txtComments” rows=”10″ cols=”60″></textarea>
</td>
</tr>
<tr>
<td>
<asp:Button id=”btnSave” runat=”server” Text=” Save ” onclick=”btnSave_Click” />
</td>
</tr>
</table>

</asp:Panel>

</ContentTemplate>

</asp:UpdatePanel>

</form>

LoginTest.aspx page(CSharp)

protected void ShowMessage(object sender, EventArgs e)
 {
 PopupLoginControl1.Visible = true;
 PopupLoginControl1.EnableModelDialog(true);
 }

//method get called when the usercontrol event get fired
 protected void PopupLoginCntl_Completed(object sender, EventArgs e)
 {
 if (PopupLoginControl1.IsLogin)
 {
 divComments.Visible = true;
 }
 else
 {
 divComments.Visible = false;
 }
 }

 protected void btnSave_Click(object sender, EventArgs e)
 {
//save your comments here.
 }

For more information about the user control event bubbling please visit the following links

http://asp.net-tutorials.com/user-controls/events/

http://codebetter.com/blogs/brendan.tompkins/archive/2004/10/06/Easily-Raise-Events-From-ASP.NET-ASCX-User-Controls.aspx

http://odetocode.com/code/94.aspx

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

You can download the entire article from here or copy paste the URL

http://www.4shared.com/file/245044652/c1777187/AjaxModelExtender.html

If you find the Ajax Modal Popup code library useful, please consider donating


Thanks
Deepu