简体   繁体   中英

Passing just once in a Page_load method

In Page_Load, I call a method that just lists some data that comes from my database. But, if I navigate through my web site, and then return to this same link that just lists some data, the method doesn't pass through the Page_Load, and then shows the old data values.

Why is my Page_Load called only once ?

My page_load

protected void Page_Load(object sender, EventArgs e)
{            
    this.CarregaList();
}

My CarregaList method

protected void CarregaList()
{
    Utilidade.Conexao con = new Utilidade.Conexao();
    dsChave.ConnectionString = con.Con;

    #region :::: Montando o Select da lista ::::

    //// Parametros do Usuário,podem ser pegos pelo token
    Utilidade.QuebraToken tk = new Utilidade.QuebraToken();

    int Acesso = Convert.ToInt32(tk.CarregaToken(15, Request.Cookies["token"].Value));
    int IdUsuario = Convert.ToInt32(tk.CarregaToken(0, Request.Cookies["token"].Value));
    int Celula = Convert.ToInt32(tk.CarregaToken(21, Request.Cookies["token"].Value));
    int Credenciada = Convert.ToInt32(tk.CarregaToken(1, Request.Cookies["token"].Value));

    StringBuilder sbSelect = new StringBuilder();

    string selectx = "SELECT top 10 San_Chave.Chave_Id, San_Chave.Usuario_Id, San_Chave.Credenciada_Id, San_Chave.Usuario_Id_Responsavel, San_Chave.DataHora, San_Chave.Transacao, " 
        + "San_Chave.Cliente_Id, San_Chave.DataHoraPegou, San_Chave.DataHoraDevolverPrevisao, San_Chave.DataHoraEntregou, San_Chave.HorasDevolucao, " 
        + "San_Chave.NomeResponsavel, San_Chave.CpfResponsavel, San_Chave.RgResponsavel, San_Chave.TelResponsavel, San_Chave.Tel2Responsavel, " 
        + "San_Chave.Endereco, San_Chave.Devolvido, San_Chave.TextoDevolucao, San_Usuario.NomeCompleto AS NomeUsuarioVenda, view_Cliente.NomeCliente " 
        + "FROM San_Chave " 
        + "JOIN San_Usuario " 
        + "ON San_Chave.Usuario_Id_Responsavel = San_Usuario.Usuario_Id "
        + "LEFT OUTER JOIN view_Cliente " 
        + "ON San_Chave.Cliente_Id = view_Cliente.Cliente_Id " 
        + "where (San_Chave.Devolvido = 0 or San_Chave.Devolvido is NULL) ";

    sbSelect.Insert(0, selectx);

    if (Acesso == 0)
    {
        sbSelect.Append(" and San_Chave.Credenciada_Id = " + Credenciada);
    }

    if (Request.QueryString["data"] != null)
    {
        sbSelect.Append(" and ( San_Usuario.NomeCompleto like '%" + Request.QueryString["data"].ToString() + "%' or San_Chave.DataHoraPegou like '%" + Request.QueryString["data"].ToString() + "%' or San_Chave.NomeResponsavel like '%" + Request.QueryString["data"].ToString() + "%' or view_Cliente.NomeCliente like '%" + Request.QueryString["data"].ToString() + "%' )");
    }

    if (Request.QueryString["transacao"] != null)
    {
        sbSelect.Append(" and San_Chave.Transacao = " + Convert.ToInt32(Request.QueryString["transacao"]));
    }

    #endregion

    dsChave.SelectCommand = sbSelect.ToString();
}

My markup

<%@ Page Title="" Language="C#" MasterPageFile="~/San/masterPage/San.Master" AutoEventWireup="true" CodeBehind="ListaChaves.aspx.cs" Inherits="Ui.San.Chaves.ListaChaves" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">            

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contentConteudo" runat="server">

<div class="divLightBox" title="Devolução de Chave" id="DevolucaoBox"></div>

<%--Aqui vem o Topo de Informaçoes da Lista--%>
<div id="InfoLista">
    <div id="InfoListaDados">
        <div id="InfoListaTabela">
            <table width="640" border="0" cellspacing="0" cellpadding="0" 
                style="margin-right: 0px">
              <tr>
                <td width="189" align="left" style="width: 440px">
                    <table border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td >
                            <input id="InputBusca" type="text" value="Procurar Chaves: Nome responsável ou data" /></td>
                        <td width="75"><img src="../tema/_Internas/imgs/btnBusca.jpg" id="btnBuscar" style="cursor:pointer;"/></td>
                      </tr>
                    </table>
                </td>
                <td width="40" align="right">
                    <table border="0" cellspacing="0" cellpadding="3" style="width: 69px">
                      <tr align="center">
                        <td>
                            <img alt="" class="style4" src="../tema/_Internas/icons/date.png" /></td>
                      </tr>
                      <tr class="FonteLegenda">
                        <td align="center">Marcar Entrega</td>
                      </tr>
                    </table>
                </td>
              </tr>    
              <tr>
                <td width="189" colspan="2" align="left" style="width: 440px">
                    <table border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td>
                                                Transação: 
                                                    <select id="transacao">
                                                        <option value="0">Venda/Aluguel</option>
                                                        <option value="1">Venda</option>
                                                        <option value="2">Aluguel</option>
                                                    </select>
                                                </td>
                      </tr>
                    </table>
                </td>
              </tr>
            </table>
        </div>
    </div>
</div>
<div>

    <p><strong>Exibindo resultado por</strong></p>
    <p><strong>Responsável ou data</strong>: <%= buscaData(Request.QueryString["data"])%> </p>
    <p><strong>Tipo de Transação</strong>: <%=  buscaTransacao(Request.QueryString["transacao"])%></p>
</div>


<asp:ListView ID="lv_chave" runat="server" DataSourceID="dsChave" 
                        EnableModelValidation="True" DataKeyNames="Chave_Id" >
                        <EmptyDataTemplate>
                            <table id="Table1" runat="server" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td>
                                        nada encontrado
                                    </td>
                                </tr>
                            </table>
                        </EmptyDataTemplate>
            <GroupTemplate>
                <tr ID="itemPlaceholderContainer" runat="server">
                    <td ID="itemPlaceholder" runat="server">
                    </td>
                </tr>
            </GroupTemplate>
                        <ItemTemplate>


<table width="680" border="0" cellspacing="0" cellpadding="0" id='boxCliente_<%# Eval("Chave_Id") %>'>
  <tr>
    <td>
    <div class="BoxDeDados <%# Eval("Chave_Id") %>">
        <div id="transacao_Id" style="display:none;"><%# Eval("Transacao")%></div>
        <div id="imovel_Id" style="display:none;"> <%# carregaImovel_Id(Eval("Chave_Id").ToString())%></div>
        <div id="cliente_Id" style="display:none;"> <%# Eval("Cliente_Id")%>  </div>

                <div class="BoxBarraTitulo">&nbsp;&nbsp;Expira em <%# Eval("HorasDevolucao")%> Hs&nbsp;&nbsp;&nbsp;Transação:</b> <%# transacao(Eval("Transacao").ToString()) %></div>
        <table width="676" border="0" cellspacing="0" cellpadding="0" class="TxtInter2">
          <tr>
            <td width="225" height="36" bgcolor="#F4F0EF" >
                &nbsp;<b>Data de retirada:</b><br />
                &nbsp;<%# Dt(Eval("DataHoraPegou").ToString(),"dddd dd/MM/yyyy") %>- <b><%# Dt(Eval("DataHoraPegou").ToString(),"HH:mm") %></b>
            </td>
            <td width="393" bgcolor="#F4F0EF">
                &nbsp;<b>Previsão de devolução:</b><br />
                &nbsp;<%# Dt(Eval("DataHoraDevolverPrevisao").ToString(), "dddd dd/MM/yyyy")%>- <b><%# Dt(Eval("DataHoraDevolverPrevisao").ToString(), "HH:mm")%></b>
            </td>
            <td width="58" bgcolor="#F4F0EF" align="center"><b>Editar<br>Status:</b></td>
          </tr>
          <tr>
            <td height="27">
                &nbsp;<span class="TxtInter3"><b>Responsável: </b><%# Responsavel(Eval("Transacao").ToString(), Eval("NomeResponsavel").ToString(), Eval("NomeUsuarioVenda").ToString())%></span>
            </td>
            <td  align="center">
                <%# carregaChaves(Eval("Chave_Id").ToString())%>
            </td>
            <td align="center" valign="top"><%# Icon(Eval("Chave_Id").ToString())%></td>
          </tr>
        </table>
    </div>
    </td>
  </tr>
</table>
                        </ItemTemplate>
                        <LayoutTemplate>

                            <table ID="groupPlaceholderContainer" runat="server" border="0" style="">
                                <tr id="Tr1" runat="server" style="">
                                    <th id="Th1" runat="server"></th>
                                </tr>
                                <tr ID="groupPlaceholder" runat="server">
                                </tr>
                            </table>                                    
                        </LayoutTemplate>
                    </asp:ListView>
    <asp:SqlDataSource ID="dsChave" runat="server"></asp:SqlDataSource>
</asp:Content>

Page_Load is always executed as it is part of the page life cycle. If you are not hitting Page_Load every time; it's probably because your page is cached.

Actually, the property IsPostback allows you to determine whether you are hitting Page_Load (or any other method) for a second time or not precisely to allow you to execute code unnecessarily when it only needs to happen once when you hit your page. This property will only be set to true when the postback is occurring within the same page. In a scenario like you describe, IsPostback should be false , meaning, with all more reason your code should execute in case you had it enclosed in a if(!IsPostBack) block but it won't execute the first time if you have it enclosed in a if(IsPostback)

UPDATE Now that you posted some code...

It's happening because your page is being cached.

Don't append strings to build your SQL statements; your are exposing your website to a SQL injection attack; among many other disadvantages of this approach.

Use parametrized queries; or create stored procs if you can.

As inferred from the comments i think you are presented with the cached version of the page by the browser to avoid this in IE9 Go to

  • Internet Options
  • Click Setting in Browing history
  • Select Every time I visit the webpage option

Since its displaying the cached version the page_load of your page is not hit. Few more tips

This should work for you.

One of the easiest ways to stop your page being cached is to add a directive to the aspx file:

<%@ OutputCache Location="None" ... %>

MSDN has more info about the OutputCache directive .

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