I am trying to use autocompletebox using ajaxToolkit autpcompleteExtender. I refer this link http://www.aspdotnet-suresh.com/2011/05/ajax-autocompleteextender-sample.html .But now I am facing two problems.
Its working fine when I use webmethod on code behind but when I try to use it from seperate webservice file its not calling their webmethod. For this I set service path also but its not working. Please check the code
.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Curriculam_Mapping.WebForm2" %>
<%# 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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:ToolkitScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
<asp:TextBox ID="txtClass" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtClass" ServiceMethod="GetCountry" ServicePath="WebService1.asmx" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" >
</cc1:AutoCompleteExtender>
</div>
</form>
</body>
</html>
.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
namespace Curriculam_Mapping
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetClass(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Select Class_Id,Title from Mst_Class where Title like #Name+'%'", con);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> ClassNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ClassNames.Add(dt.Rows[i][2].ToString());
}
return ClassNames;
}
}
}
When I use webmethod on code behind its work fine but popup not displaying properly.Its not attach to textbox control. Please check this image file
Please help me for solving this problem.
thank you.
but popup not displaying properly
This could be it is not getting the proper css for the pop-up.
Here is a link which has more about that
http://vijaysinghnegi.blogspot.in/2012/04/best-css-style-for-autocomplete.html
http://www.dotnetfox.com/articles/custom-css-style-for-ajax-autocomplete-extender-1115.aspx
Similar question on SO
A nice css style for ajax autoComplete Extender
Edit 1
Try to uncomment this line
// [System.Web.Script.Services.ScriptService]
Basically this method will be called through script and you have not allowed it to be called by java-script or jQuery.
So your code should be follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Collections.Specialized;
namespace Curriculam_Mapping
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetClass(string prefixText)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand("Select Class_Id,Title from Mst_Class where Title like #Name+'%'", con);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> ClassNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
ClassNames.Add(dt.Rows[i][1].ToString());
}
return ClassNames;
}
}
}
I got solution, just remove static keyword from web-method and its working,I don't know its a proper way or not but its working for me.
thank you for help.
Related
I'm trying to use the Ajax autoCompleteExtender to auto complete my textboxes using a sql query in my code behind. The problem I'm having is that my code behind isn't being hit at all.
What happens instead is my autocomplete options display as the code from my masterpage.
I've done some research and the problem might be that my textboxes are in an ascx file called from my aspx file but I can't figure out a way around it. I've even tried pointing the ServicePath to a webService and it still doesn't hit.
Any input would help, thank you!
Here's my relevant code:
Aspx File:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage/Admin.Master" AutoEventWireup="true" EnableEventValidation="false" %>
<%# Register TagPrefix="AdminSearch" TagName="AdminSearch" Src="AdminSearch.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<AdminSearch:AdminSearch runat="server" ID="AdminSearch" />
</asp:Content>
Ascx File:
<%# Control Language="C#" ClassName="WebUserControl" AutoEventWireup="true" EnableViewState="true" Inherits="AdminSearch" CodeBehind="AdminSearch.ascx.cs" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<link href="../Style/Search/AdminSearch.css" rel="stylesheet" />
<script src="../Scripts/js/Search/AdminSearch.js"></script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true">
</asp:ScriptManager>
<td class="g3">
<br />
<asp:TextBox ID="TextBoxTierProfile" CssClass="g3" runat="server"></asp:TextBox><br />
<cc1:AutoCompleteExtender ServiceMethod="SearchProfiles" ServicePath="~/AutoComplete.asmx"
MinimumPrefixLength="2"
CompletionInterval="1" EnableCaching="true" CompletionSetCount="10"
TargetControlID="TextBoxTierProfile"
ID="AutoCompleteExtender2" runat="server" FirstRowSelected="false">
</cc1:AutoCompleteExtender>
</td>
Asmx File:
using System.Collections.Generic;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Web;
namespace InternalTools.Admin.Search
{
/// <summary>
/// Summary description for AutoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
static string sConnection;
public AutoComplete()
{
if (HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"].ToString().Contains("127.0.0.1"))
{
sConnection = ConfigurationManager.ConnectionStrings["Reporting"].ToString();
}
else
{
sConnection = ConfigurationManager.ConnectionStrings["live"].ToString();
}
}
[System.Web.Script.Services.ScriptMethod]
[WebMethod]
public static string[] SearchProfiles(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = sConnection;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = (I've cut out the query for security reasons)
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> profiles = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
profiles.Add(sdr["PROFILENAME"].ToString());
}
}
conn.Close();
return profiles.ToArray();
}
}
}
}
}
I am trying to implement a search textbox with the Ajax Control Toolkit AutoCompleteExtender. The result should be a list of names matching the entered text however what gets displayed is the page source HTML, character by character, creating an extremely long list of single letters.
I have found and tried several samples but cannot get this to work. I am certain the database connection is valid and the SQL query when executed directly in MSSMS, returns the expected result. The AjaxControlToolkit is installed and works on other pages in the solution.
This issue was asked before ("Ajax Control Toolkit AutoCompleteExtender displays html source character by character of the current page as autocomplete suggestion list"). However for reasons of simplicity and maintainability I do not want to implement a WebService as this poster did.
acex.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoCompleteExtender - Last Names</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="txbxLastName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txbxLastName"
MinimumPrefixLength="2"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="GetLastNames">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
acex.aspx.cs
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MCA
{
public partial class acex : System.Web.UI.Page
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetLastNames(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand cmd = new SqlCommand("SELECT [Last_Name] FROM [Entity_Person] WHERE [Last_Name] LIKE #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
List<string> LastNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
LastNames.Add(dt.Rows[i][0].ToString());
}
return LastNames;
}
}
}
what i have done is login and the username appears in my masterpage in a label. what i need to do is if the logged in user has admin permission make visible controls on several child pages (including a gridview deletecontrol that is there on one child page). have be struggling to figure it out. just want to learn.
Is there a way to class all the controls under a class call admin and call from masterpage on checking user permission?
Loginpage code behind
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.Adapters;
public partial class login1 : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
}
protected void LoginButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = WCGSQL.showdata("select * from Login where Username='" + UserName.Text + "' and Password='" + Password.Text + "'");
if (ds.Tables[0].Rows.Count != 0)
{
Session["Username"] = UserName.Text;
Response.Redirect("Home.aspx");
}
else
{
FailureText.Visible = true;
FailureText.Text = "Invalid Login";
}
}
}
App/code code behind
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public class WCGSQL
{
static SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|WCG.mdf;Integrated Security=True;User Instance=True");
static public Boolean savedata(string qurt)
{
try
{
SqlCommand cmd = new SqlCommand(qurt, con);
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
static public DataSet showdata(string qurt)
{
DataSet ds = new DataSet();
try
{
SqlDataAdapter adp = new SqlDataAdapter(qurt, con);
adp.Fill(ds);
return ds;
}
catch
{
return ds;
}
}
}
You want to use the LoginView control. See ASP.NET Login Controls Overview to learn about the entire suite.
Example from MSDN:
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<p>
<asp:LoginStatus id="LoginStatus1" runat="server"></asp:LoginStatus></p>
<p>
<asp:LoginView id="LoginView1" runat="server">
<AnonymousTemplate>
Please log in for personalized information.
</AnonymousTemplate>
<LoggedInTemplate>
Thanks for logging in
<asp:LoginName id="LoginName1" runat="Server"></asp:LoginName>.
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>
<asp:LoginName id="LoginName2" runat="Server"></asp:LoginName>, you
are logged in as an administrator.
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView></p>
</form>
</body>
</html>
if (HttpContext.Current.User.IsInRole("member"))
{
//enable/disable here
}
Hey i'd done one application like this. What you need to do is make separate web-pages (i.e. after login pages) for both admin and other users. Then you can easily authenticate admin through his credentials and redirected to the respective page. There you can placed some controls according to the need.
And if your concern is to create an application like control-access board where admin can give permissions to modules to what to show on child pages of other users then let me know through your reply.
So on my ASP.NET solution's default page, I have a SlideShowExtender object, linked to a WebMethod which retrieves slides from an MSSQL database. Through debugging I can confirm that Slide objects are successfully created from said database, but once the page has loaded the SlideShow element does nothing.
Below is my code; I appreciate in advance any responses received. Thank you.
Edit: I forgot to mention that I've have verified the integrity of the Image URLs; they're correct.
Default.aspx (Default.aspx.cs is just a standard code-behind with an empty Page_Load method):
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="Dissertation._Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ToolkitScriptManager ID="scrptman" runat="server"></asp:ToolkitScriptManager>
<asp:Image ID="imgBanner" Width="800" Height="300" runat="server"/>
<br />
<asp:Label ID="lblDesc" runat="server"></asp:Label>
<asp:SlideShowExtender ID="sldShow" runat="server"
TargetControlID="imgBanner"
SlideShowServicePath="~/BannerImages.asmx"
SlideShowServiceMethod="GetPhotos"
AutoPlay="true"
ImageDescriptionLabelID="lblDesc"
Loop="true" />
</asp:Content>
BannerImages.asmx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using AjaxControlToolkit;
namespace Dissertation
{
/// <summary>
/// Summary description for BannerImages
/// </summary>
///
[System.Web.Script.Services.ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class BannerImages : System.Web.Services.WebService
{
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public Slide[] GetPhotos()
{
List<Slide> images = new List<Slide>();
ConnectionStringSettings settings = System.Configuration.ConfigurationManager.ConnectionStrings["Database"];
SqlConnection conn = new SqlConnection(settings.ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from sol_bannerData", conn);
SqlDataReader read = null;
try
{
conn.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
images.Add(new Slide(Server.MapPath("~/cms/uploads/banners/" + read["ImageURL"].ToString()), "", read["Description"].ToString()));
}
}
catch(SqlException err)
{
images.Clear();
images.Add(new Slide("", "", "Images could not be loaded: " + err.Message));
return images.ToArray();
}
finally
{
if(read != null) read.Close();
if(conn != null) conn.Close();
}
Slide[] toReturn = images.ToArray();
return toReturn;
}
}
}
Problem solved; I used jquery.cycle.all instead.
I am using Asp.Net/C#,In one of my pages I am using Ajax autocompleteextender for auto suggestions , Following is the code I am using
<Services>
<asp:ServiceReference Path="AutoCompleteSearchByName.asmx" />
</Services>
</asp:ScriptManager>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
<ajaxtoolkit:autocompleteextender runat="server" ID="autoComplete1"
TargetControlID="txtCountry" ServicePath="AutoCompleteSearchByName.asmx"
ServiceMethod="GetNames" MinimumPrefixLength="1" EnableCaching="true" />
However in the design mode it is giving me an error.The error says ,
Error creating control autocomplete1 , AutocompleteSearchByName.asmx could not be set on property ServicePath
Here is my AutoCompleteSearchByName.asmx code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace CwizBankApp
{
/// <summary>
/// Summary description for AutoCompleteSearchByName
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
//[System.Web.Script.Services.ScriptService]
public class AutoCompleteSearchByName : System.Web.Services.WebService
{
[WebMethod]
public string[] GetNames(string prefixText)
{
DataSet dst = new DataSet();
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.AppSettings["Server=Server;Database=CwizData;Trusted_Connection=True"]);
string strSql = "SELECT f_name FROM cust_master WHERE f_name LIKE '" + prefixText + "%' ";
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dst);
string[] cntName = new string[dst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dst.Tables[0].Rows)
{
cntName.SetValue(rdr["f_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
}
}
Can anybody suggest me how do I solve this issue.
Thanks
Check that you are using proper DLL for this and have look to below code aslo
IF it still not work check this article and by donlowding code check what mistake you done : AutoComplete With DataBase and AjaxControlToolkit
Try this :
<ajaxToolkit:ToolkitScriptManager ID="ScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:AutoCompleteExtender ID="autoComplete1" runat="server"
EnableCaching="true"
BehaviorID="AutoCompleteEx"
MinimumPrefixLength="2"
TargetControlID="myTextBox"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
CompletionInterval="1000"
CompletionSetCount="20"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true">
or
This not meet up with you answer but if you want you can also go for jquery soltuion here is full article for this : Cascading with jQuery AutoComplete