I am implementing auto-complete on a search box using asp.NET and c#. This is how i have divided my code: I have a class class ListSuggestions.cs, the default Default.aspx.cs class and the default page Default.aspx where my jquery autocomplete code lies.
This is my ListSuggestions.cs:
public class ListSuggestions
{
public string[] loadArray(string[] companiesArray)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand(@"SELECT [Name] FROM [Party_Company_General]", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
var companies = new List<string>();
while (dr.Read())
{
companies.Add(dr["Name"].ToString());
}
return companiesArray = companies.ToArray();
}
}
Default.aspx.cs :
public partial class Default : System.Web.UI.Page
{
private string[] companiesArray { set; get; }
public class JavaScript
{
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
}
protected void Page_Load(object sender, EventArgs e)
{
ListSuggestions listSuggestions = new ListSuggestions();
String[] companiesArray = listSuggestions.loadArray(this.companiesArray);
}
}
Default.aspx script code:
<script type="text/javascript">
$(function () {
var availableTags = <%=JavaScript.Serialize(this.companiesArray) %>
$(".searchbox").autocomplete({
source: availableTags
});
});
</script>
The problem is that i don't think the companiesArray
string is being accessible to the JavaScript code.
What might be the problem with my code?
How can i solve my problem, someone help me out please.
listSuggestions.loadArray
to end up in (just) a local variable, you need to write it to that class-level field (which must be protected or public), before the aspx code can pick it up.