mutiemule
mutiemule

Reputation: 2539

Accessing C# variables through javascript in asp.net

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.

Upvotes: 0

Views: 398

Answers (4)

mutiemule
mutiemule

Reputation: 2539

I found a solution to this. Thanks all who had helped me by giving their answers. I changed my ListSuggestions.cs to:

public string[] loadArray(ref string[] companiesArray)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
            //Fetch the field to auto complete from the database
            SqlCommand cmd = new SqlCommand(@"SELECT [Name] FROM [Party_Company_General]", conn);
            //Open connection
            conn.Open();
            //Read data from the database
            SqlDataReader dr = cmd.ExecuteReader();
            //create a list of companies
            var companiesList = new List<string>();

            while (dr.Read())
            {
                companiesList.Add(dr["Name"].ToString());
            }
            //Convert list to an array
            companiesArray = companiesList.ToArray();

            //Return the array
            return companiesArray;
        }

Also, i changed the Default.aspx.cs code to:

public partial class Default : System.Web.UI.Page
    {
        ListSuggestions listSuggestions;
        public string[] companiesArray;

        //A constructor
        public  Default()
        {
         listSuggestions= new ListSuggestions();
         companiesArray = listSuggestions.loadArray(ref companiesArray);
        }
        //Serializer
        public class JavaScript
        {
            public static string Serialize(object o)
            {
             JavaScriptSerializer js = new JavaScriptSerializer();
             return js.Serialize(o);
             }
          }
     }

I created a constructor and did away with the Page_Load method.

Lastly, i changed my script to:

<script type="text/javascript">
      $(document).ready(function () {

          var availableTags = <%=JavaScript.Serialize(companiesArray) %>

          $(".searchbox").autocomplete({
              source: availableTags
          });
      });
  </script>

Upvotes: 0

Frederik.L
Frederik.L

Reputation: 5610

What about:

public String[] CompaniesArray {
    get {
        return this.companiesArray;
    }
}

Then:

<script type="text/javascript">
    $(function () {
        var availableTags = <%=JavaScript.Serialize(CompaniesArray)%>;

        $(".searchbox").autocomplete({
            source: availableTags
        });
    });
</script>

Your array could still be private, but giving a public getter to be accessible by everyone. No risks that something will ever alterate the array from the outside of the class.

Upvotes: 0

Satpal
Satpal

Reputation: 133403

The field must be declared public/protected for proper visibility from the ASPX markup. In any case, you could declare a property:

I prefer protected and Secondly use the property to store data.

First, Change

 private string[] companiesArray { set; get; }

To:

 public string[] companiesArray { set; get; }

Change,

String[] companiesArray = listSuggestions.loadArray(this.companiesArray);

To:

companiesArray = listSuggestions.loadArray(this.companiesArray);

Change

return companiesArray = companies.ToArray();

To

return companies.ToArray();

Upvotes: 2

matt-dot-net
matt-dot-net

Reputation: 4244

String[] companiesArray is local in scope to the Page_Load method. Your Default.aspx code should be fine, but you are not actually loading anything into the class level companiesArray.

Upvotes: 1

Related Questions