简体   繁体   中英

Trying to pass a string between C# classes

I'm trying to pass a string between C# classes by using a session. I have a class called Profile and it has a search box. I have another class called SearchResults that is supposed to search my database for whatever was entered in the search box.

Upon clicking on the search button, this method in the Profile class is called:

 protected void Search(object sender, EventArgs e)
 {
     Response.Redirect("~/SearchResults.aspx");
     String searchedItem = txt_search.Text;
     Session["search"] = searchedItem;
 }

and here is the Page_Load method in the SearchResults page:

protected void Page_Load(object sender, EventArgs e)
{

    string searchedItem = (string)(Session["search"]);

    string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
    SqlConnection conn = new SqlConnection(connStr);
    SqlCommand SearchGames = new SqlCommand("SearchGames", conn);
    SearchGames.CommandType = CommandType.StoredProcedure;
    SearchGames.Parameters.Add(new SqlParameter("@game_name", searchedItem));

    conn.Open();

    SqlDataReader rdr = SearchGames.ExecuteReader(CommandBehavior.CloseConnection);

}

I'm getting an error saying that my

SearchGames procedure needs an @game_name parameter which wasn't supplied

, however it's clear that I've passed that parameter, which leads me think that there's something wrong with SearchItem (or how I'm passing the string between the two classes.

You redirect before setting the session, I think you should redirect after setting session:

String searchedItem = txt_search.Text;
Session["search"] = searchedItem;
Response.Redirect("~/SearchResults.aspx");

Rather than trying to pass the parameter via the session, inject it into the redirect:

protected void Search(object sender, EventArgs e)
{
    Response.Redirect($"~/SearchResults.aspx?search={txt_search.Text}");
}

or, if not using C# 6,

protected void Search(object sender, EventArgs e)
{
    Response.Redirect("~/SearchResults.aspx?search=" + txt_search.Text);
}

Then within Page_Load , change it to:

protected void Page_Load(object sender, EventArgs e)
{
    string searchedItem = Request.QueryString["search"];
    ...

That way, you avoid passing values through global variables, which will make the code more robust and make testing easier.

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