在Page_load方法中只传递一次

时间:2011-10-31 11:48:23

标签: c# asp.net .net

在Page_Load中,我调用的方法只列出了来自我的数据库的一些数据。但是,如果我浏览我的网站,然后返回到只列出一些数据的同一链接,该方法不会通过Page_Load,然后显示旧的数据值。

为什么我的Page_Load只调用一次?

我的page_load

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

我的CarregaList方法

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

我的标记

<%@ 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>

3 个答案:

答案 0 :(得分:2)

始终执行

Page_Load,因为它是页面生命周期的一部分。如果你没有每次都Page_Load;这可能是因为你的页面被缓存了。

实际上,属性IsPostback允许您确定是第二次点击Page_Load(或任何其他方法)还是不准确地允许您在仅需要时不必要地执行代码当你点击页面时发生一次。当在同一页面内发生回发时,此属性将仅设置为true。在您描述的方案中,IsPostback应为false,这意味着,如果您将代码包含在if(!IsPostBack)块中但赢了,您的代码应该执行更多的理由如果您将其括在if(IsPostback)

中,则第一次执行

更新现在您发布了一些代码......

这种情况正在发生,因为您的网页正在被缓存。

不附加字符串来构建SQL语句;你的网站暴露于SQL注入攻击;这种方法的许多其他缺点。

使用参数化查询;或者,如果可以的话,创建存储过程。

答案 1 :(得分:2)

从评论中推断,我认为浏览器会向您显示页面的缓存版本,以避免在IE9中出现这种情况 转到

  • 互联网选项
  • 点击浏览历史记录中的设置
  • 每次访问网页选项时选择

由于它显示了缓存版本,因此您的页面的page_load不会被点击。 Few more tips

这应该适合你。

答案 2 :(得分:1)

阻止页面缓存的最简单方法之一是向aspx文件添加指令:

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

MSDN has more info about the OutputCache directive