c# - PostBack 后 ASP.NET TextBox 值未保留 - session 值正常

标签 c# asp.net session postback

我有一个简单的 ASP.NET GridView,它数据绑定(bind)到我们数据库中的一个 View 。

选中一行后,请求将添加到 session 变量和请求 ID 文本框中。 TextBox 的 TextChanged 事件和 PostBack 事件都在我逐步完成该过程时验证了这一点,但之后这些值不会显示在网站上。

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

注意:我也曾尝试为 PostBack 事件注释掉 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>

最佳答案

发布您遇到问题的实际部分会给您更好的答案,而不是这个。

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

  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 中的控件从代码隐藏所做的任何更改(例如,通过“选择”链接回发)永远不会到达它们。

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

希望这对您有所帮助!

关于c# - PostBack 后 ASP.NET TextBox 值未保留 - session 值正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12959482/

相关文章:

c# - 通过 Windows Azure 发布后无法加载文件或程序集 System.Runtime.Serialization

c# - 包括 MySQL Connector/ODBC 5.1 到 C# 应用程序

c# - 使用 Shell32 获取文件扩展属性时出现异常

c# - PostAsync to/Token 返回内部服务器错误

javascript - 设置一天的 CSS 设计?

ASP.NET session 范围 : where can it be accessed from?

c# - 无法将类型 'void' 隐式转换为 'string'

c# - 从类型创建泛型类的实例

Java:确保 Web 应用程序仅在一个浏览器选项卡中打开

javascript - 分析和可用性软件如何做到这一点?