Home > Net >  How to remember variable value between web pages asp.net
How to remember variable value between web pages asp.net

Time:09-26

I am building an application where consultants (candidates) can be hired for specific jobs. In one table of the index page, a random candidate’s profile is loaded. On page load: HTML:

<table class="table-random-candidate">
<asp:Label ID="LblIdCandidate" runat="server" ></asp:Label>
<asp:Button ID="BtnLearnMore" runat="server" Text="Learn More" 
OnClick="BtnLearnMore_Click" />
</table>

In the CodeBehind:

Sqlquery=”SELECT TOP 1 IdCandidate, ”  
“ORDER BY NEWID”;
con.Open(); 
SqlCommand cmd = new SqlCommand(sqlquery, con);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
IdCandidateRemember=reader[“IdCandidate”].ToString();
LblIdCandidate.Text= IdCandidateRemember;
}

The candidate’s information loads correctly. This is the problem: I want the user to click on a button in the table of the candidate that will send the user to the candidate’s details page:

protected void BtnLearnMore_Click(object sender, EventArgs e)
    {
    Response.Redirect("Candidate_Details.aspx?Id="    
    IdCandidateRemember);
    }

The problem is that on BtnLearnMore_Click, the page of another candidate loads, which I assume is the next randomly selected candidate. That is, the webpage does not remember the IdCandidateRemember meant to be remembered. I’ve tried using Session and QueryString, without success, which probably just shows that I don’t really understand how those work. The pagecall works fine when I use a DataList and the following for a button in the HTML:

<asp:Button ID="BtnLearnMore" runat="server" Text="Learn More"
PostBackUrl='<%#"Candidate_Details.aspx?id=" Eval("IdCandidate")%>' 
/> 

But for this table in particular I need to use a reader Any help would be greatly appreciated!

CodePudding user response:

In this part pf the code you can use :

if (reader.Read())
{
    IdCandidateRemember=reader[“IdCandidate”].ToString();
    Session["IdCandidateRemeber"] = IdCandidateRemember; 
    LblIdCandidate.Text= IdCandidateRemember;
}

and the IdCandidateRemeber was save in the Session variable as long as the session duration, be ware to dispose the variable when finish to used

then in your botton you can use

protected void BtnLearnMore_Click(object sender, EventArgs e)
{
    Response.Redirect("Candidate_Details.aspx?Id="    
    Convert.ToString(Session["IdCandidateRemember"]));
}

if you are going to use in just one page you can use ViewState instead of Session

CodePudding user response:

ok, so this is standard fair. You have a application, user might say search for a hotel, or whatever. you display a grid.

User selects a value. Now it time to work out the details of that customer, or that project, or that order, or whatever. Plane jane database stuff - done everyday.

So while the web concept is stateless? (unlike desktop, in which your code values stay intact?

Well in web land, each page post back, your code starts from scratch each time!

So a "new" instance of the page class is created on every web request. (unless you use a ajax call to a web method - but when you do that, then your code behind can't touch nor look at any control values - since they don't exist until that page post back occures.

Ok, so what is your design pattern now?

After all, just like any application, you might click on a row, and then display details or jump to another page to say edit that choice.

there are several approaches here.

First up, and still very common?

You pass values in the url. In fact while typing this post, I can see the "message" number (value) used by the code on stack overflow in the URL.

and you still see amazon or other services OFTEN have a much of "stuff" in the url.

www.mywebsite.com?&ID=134&Account=5454444

So, you can pass values to the next web form buy using URL parameters (often called querysting values). Now the problem with this approach? Well, for certain things like a database PK value, or say even a credit card number? You don't want that information exposed to the user. Worse, the user can "mess with" and modify the values.

Now, for a general site, and say we want the population of a city? enter image description here

Ok, so lets use Session to pass the row click to the next page (say a details form to display hotel information).

so, the button click code can be this (gets the PK row id)

   protected void cmdHotelSel_Click(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        GridViewRow gRow = (GridViewRow)btn.Parent.Parent;

        int PK = (int)MyGrid.DataKeys[gRow.RowIndex]["ID"];
        Session["HotelPK"] = PK;
        Response.Redirect("ViewHotel.aspx");
    }

so, we shoved PK id into session(). (session = global = per user)

So, now on the target page, we can do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["HotelPK"] == null)
            {
                // no value - lets jump to View Hotels page
                Response.Redirect("GridRowSel.aspx");
            }
            else
            {
                ViewState["HotelPK"] = Session["HotelPK"];
                ShowHotelInfo();
            }
        }
    }

    void ShowHotelInfo()
    {
        // code here to load Hotel information from ViewState[HotelPK]
        using (SqlCommand cmdSQL =
            new SqlCommand("SELECT * FROM tblHotels WHERE ID = @ID" ,
            new SqlConnection(Properties.Settings.Default.TEST3)))
        {
            cmdSQL.Parameters.Add("@ID", SqlDbType.Int).Value = ViewState["HotelPK"];
            cmdSQL.Connection.Open();
            Repeater1.DataSource = cmdSQL.ExecuteReader();
            Repeater1.DataBind();
        }
    }

so in above, we used a repeater control to render the one hotel record.

So that "rule" of using session() to pass value(s) is ok, but note how the FIRST thing I do is transfer session to ViewState. I do this since the user could right click, or even launch another browser. So, if two hotels are open, then both pages will operate just fine and I don't care that session value(s) changed.

The other approach to persist?

We often use controls on the web page - even hidden ones. This can be often handy since client side JS code can also use such values on the page.

So, this should give you some ideas.

  • Related