大连开发区早教机构:制作一个投票系统

来源:百度文库 编辑:中财网 时间:2024/05/04 19:38:30

制作一个投票系统

例6.11  在一些文体类门户网站中,经常设立一项在线投票功能,为了在投票系统中确保准确率,防止重复投票是一项必不可少的举措。本实例将制作一个投票系统并且防止重复投票,如图6.13所示。(实例位置:光盘\TM\Instances\06\ch11)

 图6.13  在线投票

程序实现的主要步骤如下:

(1)新建一个网站,命名为ch11,默认主页名为Default.aspx。

(2)在页Default.aspx中添加一个Table表格,用来布局页面。在该Table表格上添加一个RadioButtonList控件,供用户选择投票。再添加两个Button控件,分别用于执行投票和查询投票结果。

(3)创建一个新页Result.aspx,用于显示投票结果。在该页中添加一个GridView控件用于显示投票结果。

(4)主要程序代码如下。

在页面Default.aspx中,用户单击"我要投票"按扭后,首先判断用户是否已投过票,如果用户已投票,则弹出对话框提示用户;如果用户是第一次投票,则利用Cookie对象保存用户的IP地址,并弹出对话框提示用户投票成功。代码如下:

  1. //进行投票  
  2.   protected void Button1_Click(object sender, EventArgs e)  
  3.   {  
  4.      //判断指定的IP是否已投过票了,如果已经投过了,则弹出提示对话框  
  5.      string UserIP = Request.UserHostAddress.ToString( );  
  6.     int VoteID = Convert.ToInt32(RadioButtonList1.
    SelectedIndex.ToString( ))+1;  
  7.      HttpCookie oldCookie=Request.Cookies["userIP"];  
  8.      if (oldCookie == null)  
  9.      {  
  10.        UpdateVote(VoteID);  
  11.        Response.Write("");  
  12.        //定义新的Cookie对象  
  13.        HttpCookie newnewCookie = new HttpCookie("userIP");  
  14.        newCookie.Expires = DateTime.MaxValue ;  
  15.        //添加新的Cookie变量IPaddress,值为UserIP  
  16.        newCookie.Values.Add("IPaddress", UserIP);  
  17.        //将变量写入Cookie文件中  
  18.        Response.AppendCookie(newCookie);  
  19.        return;  
  20.      }  
  21.      else  
  22.      {  
  23.        string userIP = oldCookie.Values["IPaddress"];  
  24.        if (UserIP.Trim( ) == userIP.Trim( ))  
  25.        {  
  26.           Response.Write("");  
  27.           return;  
  28.         }  
  29.         else  
  30.         {  
  31.           HttpCookie newnewCookie = new HttpCookie("userIP");  
  32.           newCookie.Values.Add("IPaddress", UserIP);  
  33.           newCookie.Expires = DateTime.MaxValue ;  
  34.           Response.AppendCookie(newCookie);  
  35.           UpdateVote(VoteID);  
  36.           Response.Write("");  
  37.           return;  
  38.         }  
  39.      }  
  40.   } 

为了使投票结果更直观,在显示投票结果页Result.aspx中,将投票结果以百分比的形式显示在页面上。实现此功能,需要将页Result.aspx切换到HTML视图中,并将自定义方法FormatVoteCount(string voteCount)绑定在显示框的百分比列中。代码如下:

  1.  
  2.                       
  3.  <%#FormatVoteCount(DataBinder.Eval(Container.
    DataItem, "NumVote").ToString ( ))%>%  
  4.                        
  5.                     

当投票结果显示框绑定时,使用自定义方法FormatVoteCount(string voteCount),将百分比列显示在界面中。代码如下:

  1. public int FormatVoteCount(string voteCount)  
  2.   {  
  3.     int total = TotalNum( );  
  4.   //如果没有被投票  
  5.    if (voteCount.Length <= 0)  
  6.    {   
  7.      //返回0个百分比  
  8.       return(0);  
  9.         
  10.     }  
  11.     if (total > 0)  
  12.     {   
  13.     //返回实际的百分比  
  14.        return (int.Parse(voteCount)*100/total);  
  15.     }  
  16.     return (0);  
  17.   }