【问题标题】:Asp.Net RadioButtonList Selected ListItem Not Recognized on Page RevisitAsp.Net RadioButtonList Selected ListItem 在页面重新访问时无法识别
【发布时间】:2011-09-03 05:02:23
【问题描述】:

在我的送货地址页面上,有两个 RadioButtonList ListItems(代码如下所示)根据用户输入写入数据库 true 或 false。

用户第一次选择一个值并进入结帐流程的下一步时,他们的收货地址类型会正确(真/假)存储在数据库中。如果他们返回送货地址页面,选择相反的 ListItem 并转到下一个结帐页面,他们更新的送货类型在数据库中不会更改。就好像 ListItem 无法识别用户的单选按钮选择在重新访问页面时发生了变化。

有人可以帮忙解决这个问题吗?

ShippingAddress.ascx

<asp:RadioButtonList id="ShipToAddressType" runat="server">
    <asp:ListItem Value="0" id="businessShipping">My shipping address is a business.</asp:ListItem>
    <asp:ListItem Value="1" id="residenceShipping">My shipping address is a residence.</asp:ListItem>
</asp:RadioButtonList>

ShippingAddress.ascx.cs

if (residenceShipping.Selected == true)
    shippingAddress.Residence = true;
else
    shippingAddress.Residence = false;

ShippingAddress.ascx.cs Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    User user = Token.Instance.User;

    Address shipAddress = null;

    foreach (Address tempAddress in user.Addresses) if (tempAddress.Nickname == "Shipping") shipAddress = tempAddress;

    // sets radio button of return users previously selected ship type
    if (shipAddress != null)
    {
        if (shipAddress.Residence == false)
        {
            ShipToAddressType.SelectedIndex = 0;
        }
        else
        {
            ShipToAddressType.SelectedIndex = 1;
        }
    }
}

【问题讨论】:

  • 该问题表明存在与页面生命周期相关的误解/错误。与给定的信息无济于事!
  • 可能需要更多信息... 代码隐藏中的 PageLoad 事件处理程序是什么样的?
  • 我编辑了帖子,在上面添加了页面加载事件处理程序。谢谢!

标签: asp.net database radiobuttonlist listitem


【解决方案1】:

您需要将Page_Load 中的代码移动到Page_Init。否则ViewState 将不起作用,您将不会收到更改事件。视图状态在Init 之后在PreLoad 之前加载。

您还应该将您的初始化代码包装在IsPostBack 检查中。虽然我可能会误解你在这里做什么。

protected void Page_Init(EventArgs e)
{
    if (!IsPostBack)
    {
        User user = Token.Instance.User;

        Address shipAddress = null;

        foreach (Address tempAddress in user.Addresses)
        {
            if (tempAddress.Nickname != "Shipping")
            {
                continue;
            }
            ShipToAddressType.SelectedIndex = 1;
        }
    }
    ShipToAddressType.SelectedIndexChanged += ShipToAddressType_SelectedIndexChanged;
}

void ShipToAddressType_SelectedIndexChanged(object sender, EventArgs e)
{
    // save the new state to database

    // redirect to enforce refresh of saved state
    Response.Redirect(Request.RawUrl);
}

【讨论】:

  • 配件手柄 CodeKing。感谢您对我长期困扰的问题的快速响应和正确回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多