skip to Main Content

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!

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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?
    http://www.mywebsite.com/ShowPopulation.aspx?City="New York"

    In the above, that works great, since the value can even be changed by the end user.

    And some large sites sill use this approach, since it costs ZERO on the server side (so for huge scalability, this choice can work).

    However, today, we have far better choices and I quite much dis-like those messy URL’s. And they can pose security issues.

    So, you can pass the row click "ID" to the next form in the URL.

    Next up?

    ViewState:

    ViewState is per page. And NOT exposed to the URL. This is thus a great choice, and i will combine why this choice is often MUCH better then the next choice.

    Session:
    Well, this one is really cherry nice. It allows you to shove variables into session(), and they persist application wide PER USER!!!

    However, you want to be careful to use session() without thinking!!!

    Say we have a grid of hotels you want to book.

    So, you can use session() to pass this hotel "ID" to the next form.

    However, now what happens if the same user launches another browser page – and selected a different hotel, and jumps to the hotel booking page. If we stored hotel ID in session()?

    It is APPLICATION wide for that one user!!! So, now with two web pages open on the hotel booking, we will have the WRONG pk id in session. And if your say about to buy a house? Then either you don’t allow the one user to have more then one house buy page open, or you ONLY use session to pass the values.

    So, what I do is use session() to pass the value(s) to the next form, and then immediate move that passed value(s) to ViewState. (because view state is per page).

    So, lets fill a grid, select a hotel from Grid, and then jump to the next page.

    So say we have this:

        <div style="width:50%;margin-left:25px;margin-top:25px">
    
        <asp:GridView ID="MyGrid" runat="server" CssClass="table table-hover" 
            DataKeyNames="ID" AutoGenerateColumns="false" OnRowDataBound="MyGrid_RowDataBound" >
            <Columns>
                <asp:BoundField DataField="FirstName"   HeaderText="FirstName"  />
                <asp:BoundField DataField="LastName"    HeaderText="Last Name" />
                <asp:BoundField DataField="HotelName"   HeaderText="Hotel Name" />
                <asp:BoundField DataField="City"        HeaderText="City" />
                <asp:BoundField DataField="Province"    HeaderText="Province" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:CheckBoxField DataField="Active"   HeaderText="Active" ItemStyle-HorizontalAlign="Center" />
    
                <asp:TemplateField >
                    <ItemTemplate>
                        <asp:Button ID="cmdHotelSel" runat="server" Text="View Hotel"
                            OnClick="cmdHotelSel_Click"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        </div>
    

    And we load up the grid in code:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
                LoadGrid();
        }
    
        public void LoadGrid()
        {
            using (SqlCommand cmdSQL = 
                new SqlCommand("SELECT * FROM tblHotels ORDER by HotelName ",
                new SqlConnection(Properties.Settings.Default.TEST3)))
            {
                cmdSQL.Connection.Open();
                MyGrid.DataSource = cmdSQL.ExecuteReader();
                MyGrid.DataBind();
            }
        }
    

    Ok, we now have this:

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search