简体   繁体   中英

ASP.NET C# Moving Method to Class File and Calling it from Code-behind

I have the following code in my aspx code-behind and it works fine. Because I am going to use it on more than one page, I'd like to move it to a class file. I am not sure how to do this properly.

#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 code-behind page like this:

BlogFrontUtil.GetCompletionList(prefixText, count, contextKey);

...but it's not working, I get the red squiggly lines. The error message says that it is a method but used like a type.

Could some one please teach me how this is done properly. I have limited experience.

Thank you

In your new class add the 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();
    }
}

Then in your service call that method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM