|
制作一個投票系統(tǒng)
例6.11 在一些文體類門戶網(wǎng)站中,經(jīng)常設(shè)立一項(xiàng)在線投票功能,為了在投票系統(tǒng)中確保準(zhǔn)確率,防止重復(fù)投票是一項(xiàng)必不可少的舉措。本實(shí)例將制作一個投票系統(tǒng)并且防止重復(fù)投票,如圖6.13所示。(實(shí)例位置:光盤\TM\Instances\06\ch11)
|
| 圖6.13 在線投票 |
程序?qū)崿F(xiàn)的主要步驟如下:
(1)新建一個網(wǎng)站,命名為ch11,默認(rèn)主頁名為Default.aspx。
(2)在頁Default.aspx中添加一個Table表格,用來布局頁面。在該Table表格上添加一個RadioButtonList控件,供用戶選擇投票。再添加兩個Button控件,分別用于執(zhí)行投票和查詢投票結(jié)果。
(3)創(chuàng)建一個新頁Result.aspx,用于顯示投票結(jié)果。在該頁中添加一個GridView控件用于顯示投票結(jié)果。
(4)主要程序代碼如下。
在頁面Default.aspx中,用戶單擊"我要投票"按扭后,首先判斷用戶是否已投過票,如果用戶已投票,則彈出對話框提示用戶;如果用戶是第一次投票,則利用Cookie對象保存用戶的IP地址,并彈出對話框提示用戶投票成功。代碼如下:
- //進(jìn)行投票
- protected void Button1_Click(object sender, EventArgs e)
- {
- //判斷指定的IP是否已投過票了,如果已經(jīng)投過了,則彈出提示對話框
- string UserIP = Request.UserHostAddress.ToString( );
- int VoteID = Convert.ToInt32(RadioButtonList1.
SelectedIndex.ToString( ))+1; - HttpCookie oldCookie=Request.Cookies["userIP"];
- if (oldCookie == null)
- {
- UpdateVote(VoteID);
- Response.Write("<script>alert('投票成功,謝謝您的參與!')</script>");
- //定義新的Cookie對象
- HttpCookie newnewCookie = new HttpCookie("userIP");
- newCookie.Expires = DateTime.MaxValue ;
- //添加新的Cookie變量IPaddress,值為UserIP
- newCookie.Values.Add("IPaddress", UserIP);
- //將變量寫入Cookie文件中
- Response.AppendCookie(newCookie);
- return;
- }
- else
- {
- string userIP = oldCookie.Values["IPaddress"];
- if (UserIP.Trim( ) == userIP.Trim( ))
- {
- Response.Write("<script>alert('一個IP地址
只能投一次票,謝謝您的參與!');history.go(-1);</script>"); - return;
- }
- else
- {
- HttpCookie newnewCookie = new HttpCookie("userIP");
- newCookie.Values.Add("IPaddress", UserIP);
- newCookie.Expires = DateTime.MaxValue ;
- Response.AppendCookie(newCookie);
- UpdateVote(VoteID);
- Response.Write("<script>alert('投票成功,謝謝您的參與!')</script>");
- return;
- }
- }
- }
為了使投票結(jié)果更直觀,在顯示投票結(jié)果頁Result.aspx中,將投票結(jié)果以百分比的形式顯示在頁面上。實(shí)現(xiàn)此功能,需要將頁Result.aspx切換到HTML視圖中,并將自定義方法FormatVoteCount(string voteCount)綁定在顯示框的百分比列中。代碼如下: - <asp:TemplateField HeaderText ="所占總票的百分比" >
- <ItemTemplate>
- <%#FormatVoteCount(DataBinder.Eval(Container.
DataItem, "NumVote").ToString ( ))%>% - </ItemTemplate>
- </asp:TemplateField>
當(dāng)投票結(jié)果顯示框綁定時,使用自定義方法FormatVoteCount(string voteCount),將百分比列顯示在界面中。代碼如下: - public int FormatVoteCount(string voteCount)
- {
- int total = TotalNum( );
- //如果沒有被投票
- if (voteCount.Length <= 0)
- {
- //返回0個百分比
- return(0);
-
- }
- if (total > 0)
- {
- //返回實(shí)際的百分比
- return (int.Parse(voteCount)*100/total);
- }
- return (0);
- }
|