Asp.Net RadioButtonList在页面重新访问时无法识别选定的ListItem

时间:2011-09-02 19:09:00

标签: asp.net database radiobuttonlist listitem

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

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

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

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

1 个答案:

答案 0 :(得分: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);
}