Redirect to another page on Ajax AutoCompleteExtender suggestion selection using C# and JavaScript in ASP.Net

Last Reply on Mar 22, 2017 08:00 AM By micah

Posted on Mar 21, 2017 11:36 PM

I want the AutoComplete image and username to be clickable, so that when i click on the image or username it will redirect to item page and display the item image and username. Somthing like this

 

 <a class="" href='<%#getUserHREF1(Container.DataItem)%>' > </a>

code to rediect

 

~/ItemPage.aspx?Id=" + Id

AutoComplete code

 

[System.Web.Script.Services.ScriptMethod()]
    [System.Web.Services.WebMethod]
    public static List<string> SearchEmployees(string prefixText, int count)
    {
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["Connection"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select Name,UserName,ImageName from User3 where " + "UserName like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefixText);
                cmd.Connection = conn;
                conn.Open();
                List<string> Searchusernames = new List<string>();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {

                        Searchusernames.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(string.Format("{0} {1}", sdr["Name"], sdr["UserName"]), sdr["ImageName"].ToString()));
                    }
                }
                conn.Close();
                return Searchusernames;
            }
        }
    }

Script

 

<script type = "text/javascript">
        function usernames_Populated(sender, e) {
            var Searchusernames = sender.get_completionList().childNodes;
            for (var i = 0; i < Searchusernames.length; i++) {
                var div = document.createElement("DIV");
                div.innerHTML = "<img style = 'height:50px;width:50px; margin-left:6px; margin-bottom:6px;' class= ' img-rounded dropdown messages-menu' src = 'PROFILEPHOTOS/"
                + Searchusernames[i]._value + "' />";
                Searchusernames[i].appendChild(div);
            }
        }
        function OnEmployeeSelected(source, eventArgs) {
            var idx = source._selectIndex;
            var Searchusernames = source.get_completionList().childNodes;
            var value = Searchusernames[idx]._value;
            var text = Searchusernames[idx].firstChild.nodeValue;
            source.get_element().value = text;
        }
</script>

 

Results 1 - 5 of 6 12
Posted on Mar 21, 2017 11:36 PM
Hi @micah,
Please try the following

Redirect to other page on click of Image Button inside GridView in ASP.Net

It might help you.

Cheers Andrea.

Posted on Mar 22, 2017 02:42 AM

What you directed me to is totally way off my question . my question is autocomplete redirect on image and username click and the autocomplete is an Ajax which uses jquery to display autocomplete .


Posted on Mar 22, 2017 06:45 AM Modified on on Nov 24, 2017 05:54 AM

Hi micah,

Refer the below sample.

HTML

CS.aspx

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script type="text/javascript">
        function usernames_Populated(sender, e) {
            var employees = sender.get_completionList().childNodes;
            for (var i = 0; i < employees.length; i++) {
                var div = document.createElement("DIV");
                div.innerHTML = "<img style = 'height:50px;width:50px' src = 'PROFILEPHOTOS/" + employees[i]._value + "' /><br />";
                employees[i].appendChild(div);
            }
        }
        function OnUserSelected(source, eventArgs) {
            var idx = source._selectIndex;
            var employees = source.get_completionList().childNodes;
            var value = employees[idx]._value;
            var text = employees[idx].firstChild.nodeValue;
            var name = text.split('~')[0]
            var id = text.split('~')[1];
            source.get_element().value = name;
            window.location.href = "ItemPage.aspx?Id=" + id;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <asp:TextBox ID="txtEmployeeSearch" runat="server"></asp:TextBox>
        <cc1:AutoCompleteExtender ServiceMethod="SearchEmployees" MinimumPrefixLength="1"
            CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtEmployeeSearch"
            OnClientPopulated="usernames_Populated" OnClientItemSelected="OnUserSelected"
            ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false">
        </cc1:AutoCompleteExtender>
    </div>
    </form>
</body>
</html>

Code

CS.aspx.cs

[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchEmployees(string prefixText, int count)
{
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select UserName,UserId,Name,ImageName from User3 where UserName like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefixText);
            cmd.Connection = conn;
            conn.Open();
            List<string> Searchusernames = new List<string>();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    Searchusernames.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(string.Format("{0}~{1}", sdr["Name"], sdr["UserId"]), sdr["ImageName"].ToString()));
                }
            }
            conn.Close();
            return Searchusernames;
        }
    }
}

ItemPage.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["Id"] != null)
    {
        Response.Write("UserId" + Request.QueryString["Id"]);
        // Fetch the user details based on userId
    }
}

Screenshot


Posted on Mar 22, 2017 07:29 AM Modified on on Mar 22, 2017 07:32 AM

URL ERROR

http://localhost:7876/MyProfile.aspx?Id=undefined

item page

 

protected void Page_Load(object sender, EventArgs e)
    {

        if (!Page.IsPostBack)
        {
            if (this.Page.User.Identity.IsAuthenticated)
            {
                string username = this.Page.User.Identity.Name;
                GetProfile(username);
            }
        }
    }

    public void GetProfile(string username)
    {
        string str = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
        string getADPOST = "GetUSERPRO2";
        using (SqlConnection con = new SqlConnection(str))
        {
            con.Open();
            using (SqlCommand cmd = new SqlCommand(getADPOST, con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
             //   cmd.Parameters.AddWithValue("@Name", Request.QueryString["Id"].ToString());
                cmd.Parameters.AddWithValue("@FriendUserName", Request.QueryString["Id"].ToString());
                cmd.Parameters.AddWithValue("@UserName", Request.QueryString["Id"].ToString());

                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable ds = new DataTable();

                da.Fill(ds);

 this is the code i use in clicking on image then its redirects to profile or item page

 

 

public string getUserHREF(object sURL)
    {
        DataRowView dRView = (DataRowView)sURL;
        string Id = dRView["UserName"].ToString();
        return ResolveUrl("~/MyProfile.aspx?Id=" + Id);
    }

 


Posted on Mar 22, 2017 07:41 AM

Now i don't know why you are getting undefined. I have provided all the information database record, project folder structure and screenshot of working sample also shown the querystring value in ItemPage.

So please check the sample and if you are missing something then modify those in your code.