ASP.NET C#将方法移动到类文件并从代码隐藏调用它

时间:2010-08-30 22:36:27

标签: c# asp.net web-services

我的aspx代码隐藏中有以下代码,它工作正常。因为我打算在多个页面上使用它,所以我想把它移到一个类文件中。我不确定如何正确地做到这一点。

#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

我尝试从代码隐藏页面调用它,如下所示:

BlogFrontUtil.GetCompletionList(prefixText,count,contextKey);

......但它没有用,我得到了红色的波浪线。错误消息表明它是一种方法,但像类型一样使用。

有人可以教我如何正确完成这项工作。我的经验有限。

谢谢

1 个答案:

答案 0 :(得分:2)

在新课程中添加方法:

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;
}