c#中RadioButtonList选中后不整体刷新页面保持选中状态

c#中用asp的RadioButtonList控件总会遇到选中了,然后跟着就刷新整体页面,又变为没有选中状态。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="demo.aspx.cs" Inherits="WebApplication2.demo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form >
    <div>
     <asp:RadioButtonList ID="rb" runat="server" AutoPostBack="false"   OnSelectedIndexChanged="displayMessage" />
     <asp:Label ID="Label1" runat="server" />
  </div>
    </form>
</body>
</html>

  后台:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class demo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //读取XML文件给chechbox赋值
            DataSet ds = new DataSet();
            ds.ReadXml(MapPath("XML.xml"));
            rb.DataSource = ds;
            rb.DataValueField = "value";
            rb.DataTextField = "text";
            rb.DataBind();
        }

        protected void displayMessage(object sender, EventArgs e)
        {
            Label1.Text = "Your favorite country is: " + rb.SelectedItem.Text;
        }
    }
}

  

就是应为AutoPostBack="true"导致的,改为AutoPostBack="false"就行。AutoPostBack="true"是表示当选中checkbox后完成后端方法然后刷新页面。

另外如果要让后台只第一次加载时执行在<%@ Page > 中加 EnableViewState="false";