用c#开发微信 (17) 微活动 3 投票活动 (文本投票)

前面介绍了微活动《大转盘》 和 《刮刮卡》,这次介绍下微投票,微投票分二种,一种是文本投票, 一种是图片投票。

 

下面介绍文本投票的详细步骤:

1. 新建文本投票活动

 

image

 

  • 代码实现:
<div  class="tab-content" >
            
                <dl>
                    <dt>投票标题:</dt>
                    <dd>
                        <asp:TextBox runat="server" ID="title" CssClass="input normal" datatype="*1-100" sucmsg=" " nullmsg=" "></asp:TextBox>
                        <span class="Validform_checktip">*</span>
                    </dd>
                </dl>
          
               
 
                <dl>
                    <dt >投票图片:</dt>
                    <dd>
                        <asp:TextBox runat="server" CssClass="input normal upload-path" ID="votepic"></asp:TextBox>
                         <div class="upload-box upload-img"></div>
                   
                    </dd>
                </dl>
 
   
                <dl>
                    <dt>
                      图片显示:
                    </dt>
                    <dd>
                         <div class="rule-multi-radio">
                        <asp:RadioButtonList ID="picdisplay" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
                            <asp:ListItem  Value="True" Selected="True">显示在投票页面</asp:ListItem>
                            <asp:ListItem  Value="False" >不显示在投票页面</asp:ListItem>
 
                        </asp:RadioButtonList>
                    </div>
                    </dd>
                </dl>
               
                <dl>
                    <dt>投票说明:</dt>
                    <dd>
                     
                  <textarea name="txtactContent" rows="2" cols="20" id="txtactContent" class="input" runat="server"></textarea>
                    <span class="Validform_checktip"></span>
                    </dd>
                </dl>
                    
 
                  <dl>
                    <dt>单选/多选:</dt>
                    <dd>
               
                         <div class="rule-multi-radio">
                        <asp:RadioButtonList ID="Radio" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
                            <asp:ListItem  Value="True" Selected="True">单选</asp:ListItem>
                            <asp:ListItem  Value="False" >多选</asp:ListItem>
 
                        </asp:RadioButtonList>
                    </div>
                    </dd>
                </dl>
                <dl>
                    <dt>截止时间:</dt>
                    <dd>
                       <div class="input-date">
                      <asp:TextBox runat="server" ID="begindate" CssClass="input date" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" datatype="*1-50" errormsg="请选择正确的日期" sucmsg=" " nullmsg=" "></asp:TextBox>
                      </div>
                      <div class="input-date">
                      <asp:TextBox runat="server" ID="enddate" CssClass="input date" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss'})" datatype="*1-50" errormsg="请选择正确的日期" sucmsg=" " nullmsg=" "></asp:TextBox>
                      </div>
                        <span class="Validform_checktip">*</span>
                    </dd>
                </dl>
                <dl>
                    <dt>投票结果:</dt>
                    <dd>
                        <div class="rule-multi-radio">
                        <asp:RadioButtonList ID="resultShowtype" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
                            <asp:ListItem  Value="1" Selected="True" >投票前可见</asp:ListItem>
                            <asp:ListItem  Value="2" >投票后可见</asp:ListItem>
                            <asp:ListItem  Value="3" >投票结束可见</asp:ListItem>
                        </asp:RadioButtonList>
                    </div>
                      
                    </dd>
                </dl>
 
              <dl style="display:none">
                    <dt>投票后参加活动:</dt>
                    <dd>
                      <asp:TextBox runat="server" CssClass="input normal upload-path" ID="actUrl"></asp:TextBox>
                      
                    </dd>
                </dl>
 
        </div>

 

2. 设置投票的选项

image

  • 代码实现:
<div class="tab-content" style="display: none">
 
               <dl>
                <dt>选项标题</dt>
                <dd>选项标题:<asp:TextBox ID="xuanxtitle1" runat="server" CssClass="input "  datatype="*1-100" sucmsg=" " Text="" />
                    排序:<asp:TextBox ID="Sortid1" runat="server" CssClass="input small" datatype="n" sucmsg=" " Text="" nullmsg=" " />
                    <span class="Validform_checktip">*必填项</span>
                </dd>
            </dl>
 
          <dl>
                <dt>选项标题</dt>
                <dd>选项标题:<asp:TextBox ID="xuanxtitle2" runat="server" CssClass="input " datatype="*1-20" sucmsg=" " Text="" />
                    排序:<asp:TextBox ID="Sortid2" runat="server" CssClass="input small " datatype="n" sucmsg=" " Text="" nullmsg=" " />
                    <span class="Validform_checktip">*必填项</span>
                </dd>
            </dl>
 
                   <dl>
                <dt>选项标题</dt>
                <dd>选项标题:<asp:TextBox ID="xuanxtitle3" runat="server" CssClass="input " datatype="*0-100"  sucmsg=" " Text="" />
                    排序:<asp:TextBox ID="Sortid3" runat="server" CssClass="input small" datatype="/^\d*$/"  sucmsg=" " Text="" />
                    
                </dd>
              </dl>
 
                <dl>
                <dt>选项标题</dt>
                <dd>选项标题:<asp:TextBox ID="xuanxtitle4" runat="server" CssClass="input " datatype="*0-100"  sucmsg=" " Text="" />
                    排序:<asp:TextBox ID="Sortid4" runat="server" CssClass="input small" datatype="/^\d*$/"  sucmsg=" " Text="" />
               
                </dd>
              </dl>
               <dl>
                <dt>选项标题</dt>
                <dd>选项标题:<asp:TextBox ID="xuanxtitle5" runat="server" CssClass="input " datatype="*0-100"  sucmsg=" " Text="" />
                    排序:<asp:TextBox ID="Sortid5" runat="server" CssClass="input small"  datatype="/^\d*$/" sucmsg=" " Text="" />
                   
                </dd>
              </dl>
 
              <dl>
                <dt>选项标题</dt>
                <dd>选项标题:<asp:TextBox ID="xuanxtitle6" runat="server" CssClass="input " datatype="*0-100"  sucmsg=" " Text="" />
                    排序:<asp:TextBox ID="Sortid6" runat="server" CssClass="input small"  datatype="/^\d*$/" sucmsg=" " Text="" />
                  
                </dd>
              </dl>
 
        </div>

 

3. 设置完成后出现在列表里

image 

4. 把上面生成的外链代码发送给微信用户

用户收到投票的消息,点击进入后就可以投票了

Screenshot_2015-06-11-22-04-25

代码实现:

  • 前台显示
<div class="vote">
        <form class="form" target="_top" runat="server" enctype="multipart/form-data">
            <div class="votecontent">
                <h2><%=baseinfo.title %></h2>
                <span class="date"><%=baseinfo.creatDate.Value.ToString("yyyy-MM-dd") %></span>
                <p class="content" id="content"><%=baseinfo.votecontent %></p>
 
                <script src="js/play.js" type="text/javascript"></script>
                <p class="modus">单选投票,<span class="number">共有<%=toupNum %>参与投票</span></p>
                <ul class="list" id="list">
                    <asp:Literal ID="litChooes" runat="server"></asp:Literal>
                    <asp:Literal ID="litMessageList" runat="server" EnableViewState="false"></asp:Literal>
                </ul> 
                <asp:Literal ID="litSubmitBtn" runat="server" EnableViewState="false"></asp:Literal>
                <input class="pxbtn" name="button" runat="server" type="button" id="btnSubmit" value="确认提交">
            </div>
        </form>
    </div> 

 

  • 后台绑定数据:
public void BindData(int wid, int aid, string openid)
       {
           //基本表信息
           BLL.wx_vote_base baseBll = new BLL.wx_vote_base();
           List<Model.wx_vote_base> mlist = baseBll.GetModelList(string.Format(" id={0} and wid={1} ", aid, wid));
           if (mlist.Count <= 0 || mlist == null)
           {
               return;
           }
           baseinfo = mlist[0];
           //投票选项字符串设置
           BLL.wx_vote_item itemBll = new BLL.wx_vote_item();
           IList<Model.wx_vote_item> itemlist = itemBll.GetModelList("baseid=" + baseinfo.id);
           if (itemlist == null || itemlist.Count <= 0)
           {
               return;
           }
           ItemListStr(itemlist, openid);
       }
 
public void ItemListStr(IList<Model.wx_vote_item> itemlist, string openid)
        {
            toupNum = itemlist.Sum(i => i.tpTimes == null ? 0 : i.tpTimes).Value;
 
            BLL.wx_vote_result retBll = new BLL.wx_vote_result();
            IList<Model.wx_vote_result> retList = retBll.GetModelList("baseid=" + baseinfo.id);
            //投票总数
 
            // int ttCount = retList == null ? 0 : retList.Count;
            //toupNum = retBll.GetVotedPersonNum(baseinfo.id);
            int itemCount = 0;
            float bfb = 0;
            hasVoted = false;
            bool showReult = false;
 
 
            //判断这个人是否已经投票了
            IList<Model.wx_vote_result> myretList = (from r in retList where r.openId == openid select r).ToArray<Model.wx_vote_result>();
            if (myretList != null && myretList.Count > 0)
            {
                hasVoted = true;
            }
 
            //判断是否显示结果
            if (baseinfo.resultShowtype == 1)
            {
                showReult = true;
            }
            else if (baseinfo.resultShowtype == 2 && hasVoted)
            {
                showReult = true;
            }
            else if (baseinfo.resultShowtype == 3 && baseinfo.endTime <= DateTime.Now)
            {
                showReult = true;
            }
            StringBuilder sb = new StringBuilder();
            StringBuilder choose = new StringBuilder();
            
                Model.wx_vote_item item = new Model.wx_vote_item();
                for (int i = 0; i < itemlist.Count; i++)
                {
                    item = itemlist[i];
                    itemCount = item.tpTimes == null ? 0 : item.tpTimes.Value;
                    bfb = computeBL(toupNum, itemCount);
                    sb.Append("<li>");
                    if (showReult)//投票了
                    { 
                        sb.Append(" <label for=\"square-checkbox-" + i + "\">");
                        if (!showReult || (baseinfo.resultShowtype == 1 && !hasVoted))
                        {
                            sb.Append("<input class=\"ckbx\" tabindex=\"9\" name=\"id[]\" value=\"" + (i + 1) + "\" type=\"radio\" id=\"square-checkbox-" + i + "\">");
                        }
                        sb.Append(" <span>" + item.title + "</span>");
                        sb.Append("  </label>");
                        sb.Append("  <div id=\"voteshow" + i + "\" class=\"votebar\">");
                        sb.Append("     <div class=\"pbg\">");
                        sb.Append("         <div style=\"width: " + bfb + "%; background-color:" + bkColor(i) + "\" class=\"pbr\"></div>");
                        sb.Append("     </div>");
                        sb.Append("      <span class=\"percentage\" style=\"color: " + bkColor(i) + "\">" + bfb + "%<span class=\"user\">(" + itemCount + ")</span></span>");
                        sb.Append(" </div>"); 
                    }
                    else
                    {
                        sb.Append(" <label for=\"square-checkbox-" + i + "\">"); 
                        if (!showReult || (baseinfo.resultShowtype == 1 && !hasVoted))
                        {
                            sb.Append(" <input class=\"ckbx\" tabindex=\"9\" name=\"id[]\" value=\"" + (i + 1) + "\" type=\"" + chektype() + "\" id=\"square-checkbox-" + i + "\">");
                        }
                        sb.Append(" <span>" + item.title + "</span>");
                        sb.Append("  </label>");
                    }
 
                    sb.Append(" </li>");
 
                }
     
 
            if (hasVoted)
                this.btnSubmit.Visible = false;
 
            if (baseinfo.resultShowtype == 3 && baseinfo.endTime > DateTime.Now && hasVoted)
            {
                Response.Redirect("tp_result.aspx");
            }
 
            litMessageList.Text = sb.ToString();
        }

 

 

投票成功后提示

Screenshot_2015-06-11-22-04-41

 

  • 投票成功
<script>
    $(document).ready(function () {
        $(".ckbx").click(function () {
            var i = 0;
            var aa = document.getElementsByName('id[]');
            var mnum = aa.length;
            j = 0;
            for (i = 0; i < mnum; i++) {
                if (aa[i].checked) {
                    j++;
                }
            }
            if (j > 2) {
 
                $(this).attr("checked", false);
 
            }
        });
    });
    $(document).ready(function () {
 
        var isradio = $('input:radio[class="ckbx"]:checked').val();
 
        $("#btnSubmit").click(function () {
            var wid = $.query.get("wid");
            var openid = $.query.get("openid");
            var aid = $.query.get("aid");
            var selectItemid = "";
 
            if (isradio == "true") {
                var list = $('input:radio[class="ckbx"]:checked').val();
 
                if (list == null) {
                    alert("请选中一个!");
                    return false;
                }
                else {
                    selectItemid = list;
                }
            }
            else {
                $('input[class="ckbx"]:checked').each(function () {
                    selectItemid += $(this).val() + ',';
                });
                if (selectItemid == "") {
                    alert("请选中一个!");
                    return;
                }
                if (selectItemid.length > 0) {
                    selectItemid = selectItemid.substring(0, selectItemid.length - 1);
                }
            }
            var submitData = {
                wid: wid,
                openid: openid,
                baseid: aid,
                itemid: selectItemid,
                isradio: isradio,
                myact: "commit"
            }; 
            $.post('vote.ashx', submitData,
         function (data) {
             if (data.ret == "ok") {
                 alert(data.content);
                 window.location.href = location.href;
             } else { alert(data.content); }
         },
         "json")
        });
    });
    </script>

 

  • 插入DB:
public class vote : IHttpHandler
    {
 
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            string _action = MyCommFun.QueryString("myact");
            string openid = MyCommFun.RequestOpenid();  //得到微信用户的openid
            Dictionary<string, string> jsonDict = new Dictionary<string, string>();
 
            if (_action == "commit")
            { //提交投票
                int wid = MyCommFun.RequestInt("wid");
                int baseid = MyCommFun.RequestInt("baseid");
                string itemid = HttpContext.Current.Request["itemid"].ToString();
 
                BLL.wx_vote_result resultBll = new BLL.wx_vote_result();
                Model.wx_vote_result result = new Model.wx_vote_result();
                BLL.wx_vote_item iBll = new BLL.wx_vote_item();
 
                if (MyCommFun.QueryString("isradio") == "true")
                {
                    result.baseid = baseid;
                    result.itemid = Convert.ToInt32(itemid);
                    result.openId = openid;
                    result.createDate = DateTime.Now;
                    resultBll.Add(result);
                    iBll.Update(result.itemid.Value, result.baseid.Value);
                }
                else
                {
                    string[] sArray = itemid.Split(',');
                    for (int i = 0; i < sArray.Length; i++)
                    {
                        result.baseid = baseid;
                        result.itemid = Convert.ToInt32(sArray[i]);
                        result.openId = openid;
                        result.createDate = DateTime.Now;
                        resultBll.Add(result);
                        iBll.Update(result.itemid.Value, result.baseid.Value);
                    }
 
                }
 
                //AddAdminLog(MXEnums.ActionEnum.Add.ToString(), ""); //记录日志
 
 
                jsonDict.Add("ret", "ok");
                jsonDict.Add("content", "投票成功");
 
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
 
            }
        }
 
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

因为前面设置的是投票完成后才可以看到投票结果,所以这里投完票后会显示投票的结果

 

 

 

 

Screenshot_2015-06-11-22-05-08

 

 

  • 计算投票数比例
protected float computeBL(int ttCount, int itemCount)
        {
            if (ttCount == 0)
            {
                return (float)0.00;
            }
 
            float ret = (itemCount * 100.0f) / ttCount;
 
            ret = (float)Math.Round(ret, 2);
 
            return ret;
 
 
        }

 

 

 

 

 

 

 

 

用c#开发微信 系列汇总

posted @ 2015-06-12 09:15  疯吻IT  阅读(4519)  评论(2编辑  收藏  举报