ASP.NET C # Moving a Method to a Class File and Calling It from Code

I have code in my aspx code and it works great. Since I am going to use it on multiple pages, I would like to move it to a class file. I'm not sure how to do it right.

#region autocomplete search

[WebMethodAttribute(), ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
    SqlConnection con;
    SqlCommand cmd;
    string cmdString = "SELECT TOP(15) Title FROM posts WHERE (Title LIKE '%" + prefixText + "%') OR (Content LIKE '%" + prefixText + "%')";
    con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbMyCMSConnectionString"].ConnectionString);

    cmd = new SqlCommand(cmdString, con);
    con.Open();

    SqlDataReader myReader;
    List<string> returnData = new List<string>();

    myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    while (myReader.Read())
    {
        returnData.Add(myReader["Title"].ToString());
    }

    myReader.Close();
    con.Close();

    return returnData.ToArray();
}

#endregion

I tried calling it from the page with the code below:

BlogFrontUtil.GetCompletionList (prefixText, count, contextKey);

... but it doesn't work, I get red squiggly lines. The error message says it is a method, but used as a type.

Can someone please teach me how to do it right. I have limited experience.

thank

+3
source share
1 answer

In the new class, add a method:

public static class NewClass
{
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        SqlConnection con;
        SqlCommand cmd;
        string cmdString = "SELECT TOP(15) Title FROM posts WHERE (Title LIKE '%" + prefixText + "%') OR (Content LIKE '%" + prefixText + "%')";
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbMyCMSConnectionString"].ConnectionString);

        cmd = new SqlCommand(cmdString, con);
        con.Open();

        SqlDataReader myReader;
        List<string> returnData = new List<string>();

        myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);

        while (myReader.Read())
        {
            returnData.Add(myReader["Title"].ToString());
        }

        myReader.Close();
        con.Close();

        return returnData.ToArray();
    }
}

:

[WebMethodAttribute(), ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
    string[] s = NewClass.GetCompletionList(prefixText, count, contectKey);
    return s;
}
+2

Source: https://habr.com/ru/post/1762367/


All Articles