PostBack后没有保留ASP.NET TextBox值 - 会话值OK

时间:2012-10-18 16:37:10

标签: c# asp.net session postback

我有一个简单的ASP.NET GridView,它被数据绑定到我们数据库的视图。

选择行时,会将Request添加到Session变量和Request ID TextBox。当我逐步完成整个过程时,TextBox的TextChanged事件和PostBack事件都会对此进行验证,但之后不会在网站上显示这些值。

代码发布在.NET Pad上:http://dotnetpad.net/ViewPaste/TJp2pldPkk6poP3cVzRlHQ

注意:我也尝试在Post_Lack事件的Page_Load中注释掉所有代码,但这并没有解决我的问题。

什么可以使这项工作?

代码:

<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ import Namespace="System.Web.UI.WebControls" %>
<script runat="server">

  protected void Page_Load(object sender, EventArgs e) {
    if (IsPostBack) {
      //int nDDL = GetInteger(Session[ddlSelector.ID]);
      //if (nDDL == ddlSelector.SelectedIndex) {
      //  int reqID = GetInteger(Session[txtRequestID.ID]);
      //  if ((0 < reqID) && (reqID.ToString() != txtRequestID.Text)) {
      //    string strEmp = IsNumeric(Session[txtEmployee.ID]) ? GetText(Session[txtEmployee.ID]) : null;
      //    txtRequestID.Text = reqID.ToString();
      //    txtEmployee.Text = strEmp;
      //    if (nDDL != ddlChangeTo.SelectedIndex) {
      //      ddlChangeTo.SelectedIndex = nDDL;
      //    }
      //  }
      //}
    } else {
      Session[ddlSelector.ID] = null;
      Session[txtRequestID.ID] = null;
      Session[txtEmployee.ID] = null;
      txtRequestID.Text = null;
      txtEmployee.Text = null;
      txtMTF.Text = null;
      btnOK.Visible = (0 < GetInteger(txtRequestID.Text));
    }
  }

  private void ErrorMessage(string message) {
    Response.Write(string.Format("<font color=\"Red\"><b>{0}</b></font>", message));
  }

  protected void GridViewRow_Selected(object sender, EventArgs e) {
    var row = GridView1.SelectedRow;
    if (row != null) {
      var reqIdCell = row.Cells[1];
      if (reqIdCell != null) {
        int reqID = GetInteger(reqIdCell.Text);
        if (0 < reqID) {
          Session[ddlSelector.ID] = ddlSelector.SelectedIndex;
          Session[txtRequestID.ID] = reqID;
          txtRequestID.Text = reqID.ToString();
          txtEmployee.Text = null;
          btnOK.Visible = true;
        }
      }
    }
  }

  protected void Submit_Click(object sender, EventArgs e) {
    int reqID = GetInteger(Session[txtRequestID.ID]);
    if (0 < reqID) {
      ErrorMessage("Success!");
    } else {
      ErrorMessage("Unrecognised Request ID.");
      txtRequestID.Focus();
    }
  }

  protected void TextBox_TextChanged(object sender, EventArgs e) {
    if (sender is TextBox) {
      TextBox tbx = (TextBox)sender;
      if (tbx.ID == txtRequestID.ID) {
        int reqID = GetInteger(txtRequestID.Text.Trim());
        int reqI2 = GetInteger(Session[txtRequestID.ID]);
        if (0 < reqID) {
          Session[txtRequestID.ID] = reqID;
        } else {
          txtRequestID.Text = null;
        }
        if (0 < reqI2) {
          txtRequestID.Text = reqI2.ToString();
        }
      } else if (tbx.ID == txtEmployee.ID) {
        string empNum = txtEmployee.Text.Trim();
        if (IsNumeric(empNum)) {
          Session[txtEmployee.ID] = empNum;
        } else {
          txtEmployee.Text = null;
        }
      }
    } else if (sender is DropDownList) {
      DropDownList ddl = (DropDownList)sender;
      if (ddl.ID == ddlSelector.ID) {
        Session[ddlSelector.ID] = ddlSelector.SelectedIndex;
        Session[txtRequestID.ID] = null;
        Session[txtEmployee.ID] = null;
      }
    }
  }

  protected void Tick_Tock(object sender, EventArgs e) {
    GridView1.DataBind();
  }

  private static int GetInteger(object value) {
    int result = -1;
    if (HasValue(value)) {
      try {
        result = (int)value;
      } catch {
        result = -1;
      }
    }
    if (result == -1) {
      result = 0; // errors could occur if I try indexing things with negative numbers
      string text = GetText(value);
      if (!String.IsNullOrEmpty(text)) {
        int.TryParse(text.Trim(), out result);
      }
    }
    return result;
  }

  private static string GetText(object value) {
    if (HasValue(value)) {
      return value.ToString().Trim();
    }
    return null;
  }

  private static bool HasValue(object item) {
    if ((item != null) && (item != DBNull.Value)) {
      return !String.IsNullOrEmpty(item.ToString().Trim());
    }
    return false;
  }

  private static bool IsNumeric(object input) {
    if (input == null) return false;
    string text = input.ToString();
    if (!String.IsNullOrEmpty(text.Trim())) {
      foreach (char c in text.ToCharArray()) {
        if (char.IsLetter(c)) return false;
      }
    }
    return true;
  }

</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      <asp:SqlDataSource ID="productionDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CPWEB_PRODUCTION %>" SelectCommand="SELECT [RequestID], [Employee], [DateStamp], [Line], [PartNo], [Workorder], [Qty], [MTF], [Status] FROM [vwRequestsEx] WHERE ([Status] = @Status)"><SelectParameters>
          <asp:ControlParameter ControlID="ddlSelector" Name="Status" PropertyName="SelectedValue" Type="String" />
        </SelectParameters></asp:SqlDataSource>
      <asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />
      <table style="width: 90%">
        <tr>
          <td>Display:<br /><asp:DropDownList ID="ddlSelector" runat="server" DataSourceID="productionStatus2" DataTextField="Description" DataValueField="Description" OnSelectedIndexChanged="TextBox_TextChanged"></asp:DropDownList>
            <asp:SqlDataSource ID="productionStatus2" runat="server" ConnectionString="<%$ ConnectionStrings:CPWEB_PRODUCTION %>" SelectCommand="SELECT [ID], [Description] FROM [Status]"></asp:SqlDataSource>
          </td>
          <td>RequestID:<br /><asp:TextBox ID="txtRequestID" runat="server" OnTextChanged="TextBox_TextChanged" AutoCompleteType="Disabled" /></td>
          <td>Employee:<br /><asp:TextBox ID="txtEmployee" runat="server" OnTextChanged="TextBox_TextChanged" AutoCompleteType="Disabled" /></td>
          <td>MTF:<br /><asp:TextBox ID="txtMTF" runat="server" OnTextChanged="TextBox_TextChanged" AutoCompleteType="Disabled" /></td>
          <td style="width: 110px;">Change To:<br /><asp:DropDownList ID="ddlChangeTo" runat="server" DataSourceID="productionStatus3" DataTextField="Description" DataValueField="Description"></asp:DropDownList>
            <asp:SqlDataSource ID="productionStatus3" runat="server" ConnectionString="<%$ ConnectionStrings:CPWEB_PRODUCTION %>" SelectCommand="SELECT [Description] FROM [Status] WHERE ([Description] &lt;&gt; @Description)"><SelectParameters>
              <asp:ControlParameter ControlID="ddlSelector" Name="Description" PropertyName="SelectedValue" Type="String" />
            </SelectParameters></asp:SqlDataSource>
          </td>
          <td><br />
            <asp:Button ID="btnOK" runat="server" Text="Submit" OnClick="Submit_Click" Width="75px" /></td>
        </tr>
        <tr>
          <td class="nowrap" colspan="6">
            <asp:Timer ID="Timer1" OnTick="Tick_Tock" runat="server" Interval="30000"></asp:Timer>
            <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
              <Triggers><asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /></Triggers>
              <ContentTemplate>
            <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" AutoGenerateSelectButton="True" CellPadding="1" DataSourceID="productionDataSource2" EmptyDataText="No Records to Display" Font-Size="Small" ForeColor="#333333" OnSelectedIndexChanged="GridViewRow_Selected" ShowHeaderWhenEmpty="True" HorizontalAlign="Left" RowHeaderColumn="RequestID" Width="95%">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
              <asp:BoundField DataField="RequestID" HeaderText="RequestID" SortExpression="RequestID" />
              <asp:BoundField DataField="Employee" HeaderText="Employee" SortExpression="Employee" />
              <asp:BoundField DataField="DateStamp" HeaderText="DateStamp" SortExpression="DateStamp" />
              <asp:BoundField DataField="Line" HeaderText="Line" SortExpression="Line" />
              <asp:BoundField DataField="PartNo" HeaderText="PartNo" SortExpression="PartNo" />
              <asp:BoundField DataField="Workorder" HeaderText="Workorder" SortExpression="Workorder" />
              <asp:BoundField DataField="Qty" HeaderText="Qty" SortExpression="Qty" />
              <asp:BoundField DataField="MTF" HeaderText="MTF" SortExpression="MTF" />
              <asp:BoundField DataField="Status" HeaderText="Status" SortExpression="Status" />
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Left" Wrap="False" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle><SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle><SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle><SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle></asp:GridView></ContentTemplate></asp:UpdatePanel></td>
        </tr>
      </table>
    </div>
  </form>
</body>
</html>

1 个答案:

答案 0 :(得分:4)

发布您遇到问题的实际部分会让您更好地回答这个问题。

你不需要所有其他部分,只需这样做

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
         //code to execute here only when an action is taken by the user
         //and not affected by PostBack
    }

    //these codes should be affected by PostBack
 }

希望它有所帮助!

<强>更新

我相信您的UpdatePanel是造成问题的原因。删除UpdatePanel,看起来没问题。

顶部的原因控件没有被更新是因为它们不在UpdatePanel中,你通过UpdatePanel中的控件从代码隐藏中做出的任何更改(例如,通过“选择”链接的PostBack)将永远不会到达它们。 / p>

一种解决方案是在顶部包括那些控件,例如: UpdatePanel中的RequestID文本框。

希望这有帮助!