mvc4中使用angularjs实现一个投票系统

时间:2022-12-10 23:49:01

数据库是用EF操作,数据表都很简单中,从代码中也能猜出表的结构,所以关于数据库表就不列出了

投票系统实现还是比较简单,投票部分使用ajax实现,评论部分是使用angularjs实现,并且页面每隔几秒(可以自己间隔时间)就从服务器异步获取评论数据,并通过angularjs的双向绑定功能自动更新数据(这部分其实完全可以使用websocket - singarlR完成,将更加简洁).评论是按分页显示,所以还使用到了pagedList组件,具体可以看我以前部分。

 mvc4中使用angularjs实现一个投票系统

使用到的 js

    <link href="~/Content/css/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script src="~/Content/js/bootstrap.min.js"></script>
    <script src="~/Scripts/angularjs.js"></script>

视图:

@{
    ViewBag.Title = "Index";
}
@using PagedList.Mvc
@model PagedList.IPagedList<Vote.Models.Comment>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    body {
        /*background: #eff3f5;*/
        background: url(/content/images/abc2.jpg);
        font-size: 16px;
    }

    label {
        cursor: pointer;
        height: 40px;
    }

    h3 {
        color: #888;
        background: #eff3f5;
        height: 50px;
        line-height: 50px;
        padding-left: 10px;
    }


    .emitTime {
        clear: both;
        font-size: 14px;
        color: #888;
        margin-top: 20px;
    }
</style>
<div class="container" style="width: 800px; margin: 0 auto; background: white; padding-left: 0; padding-right: 0; " ng-app="app">
    <div ng-controller="myController">
        <div class="text-center well" style="padding:0;">
            <h3 style="text-align:left;background:#fff;margin:0;">投票</h3>
            <h2 style="padding-top:20px;">@ViewBag.voteTitle</h2>
            <div style="margin: 30px; text-align: left">
                @foreach (var item in ViewBag.voteItems)
                {
                    <label for="@item.id">
                        <input type="radio" id="@item.id" name="vote" /> @item.item
                        <small style="color:#888">
                            (                            @item.num 票 )
                        </small>
                    </label><br />
                }
            </div>
            <button id="btnVote" class="btn btn-primary btn-lg" style="width:120px;margin-bottom:20px;">确定提交</button>
        </div>
        <div style="margin:0 auto;text-align:center;">
            <h3 class="text-left">发表评论</h3>
            <textarea id="usercomment" style="width: 98%; margin: 0 auto; border: 1px solid #0094ff; border-radius: 5px; padding: 3px; box-shadow:rgba(0,0,0,0.2) 5px 5px 5px;" name="answer" placeholder="说两句。。。。"></textarea>
            <button class="btn btn-info btn-lg text-left " style="width:80px;margin-top:10px;" ng-click="addComment()">发表</button>
        </div>
        <hr />
        <div id="comment">
            <h3>评论</h3>
            @if (Model != null)
            {
                <div class="pagedList" style="margin:0 auto;text-align:center">
                    @Html.PagedListPager(Model, page => Url.Action("index", new { page }), PagedListRenderOptions.Classic)
                </div>
            }

            <div class="userContents" style="width:97%;margin:0 auto">
                <div ng-repeat="item in list">
                    <div class="row">
                        <div class="col-md-1" style="margin:0 auto;"><img src="/content/images/head.png" class="img-circle" /></div>
                        <div class="col-md-11" style="line-height: 30px; padding-left: 20px; padding-right: 20px; ">
                            {{item.contents}}
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-1"></div>
                        <div class="col-md-11 emitTime">
                            发表时间:{{item.emit}}
                        </div>
                    </div>
                    <hr />
                </div>
            </div>
        </div>
    </div>
</div>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<input id="pagenum" value="@ViewBag.pagenum" />

<script>
    var page = '@ViewBag.page' || 1;

    $("#btnVote").click(function () {

        var id = $(":radio[name=vote]:checked").attr("id");

        $.post("/home/vote", { id: id }, function (data) {
            if (data == "ok") {
                alert("ok");
                location.href = "/home/index";
            } else {
                alert(data);
            }
        });
    });

    var app = angular.module("app", []);

    app.controller("myController", function ($scope, $http, $interval) {


        $scope.list = [];

        $http({
            url: '/home/data',
            metho: 'get',
            params: { 'page': page }
        }).then(function (res) {
            $scope.list = res.data;
        });



        $scope.addComment = function () {
            var txt = $("#usercomment").val();
            $.post("/home/addcomment", { contents: txt }, function (data) {
                if (data == "ok") {
                    location.href = "/home/index";
                } else {
                    alert(data);
                }
            });
        };
        $interval(function () {
            $http({
                url: '/home/data',
                metho: 'get',
                params: { 'page': page }
            }).then(function (res) {
                $scope.list = res.data;
            });
        }, 5000);

    });
</script>

Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vote.Models;
using PagedList;
using System.Net;

namespace Vote.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        VoteEntities db = new VoteEntities();
        private const int pagesize = 2;

        /// <summary>
        /// angularjs获取数据
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public JsonResult Data(int page = 1)
        {
            var list = db.Comments.OrderByDescending(x => x.id).ToPagedList<Comment>(page, pagesize);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        //用户投票结果添加
        public ActionResult vote(int id=0)
        {
            if ( id < 1)
            {
                return Content("无效投票");
            }
            if (Request.IsAjaxRequest())
            {

                var userip = GetIP();
                var isExist = db.IPS.Find(userip);
                if (isExist != null)
                {
                    return Content("你已经投过票了,每个电脑只能投票一次");
                }
                db.IPS.Add(new IP() { IP1 = userip });
                var item = db.VoteItems.Find(id);
                item.num++;
                db.SaveChanges();

                return Content("ok");
            }
            return Content("无权操作");
        }
        //视图
        public ActionResult Index(int page = 1)
        {
            var list = db.Comments.OrderByDescending(x => x.id).ToPagedList<Comment>(page, pagesize);
            ViewBag.page = page;

            ViewBag.voteTitle = db.VoteTitles.FirstOrDefault().title;
            ViewBag.voteItems = db.VoteItems.ToList();

            return View(list);
        }

        //用户添加评论
        public ActionResult addcomment(Comment c)
        {
            if (Request.IsAjaxRequest())
            {
                try
                {
                    var now = DateTime.Now;

                    c.addtime = now;
                    c.emit = now.ToString("yyyy-MM-dd HH:mm:ss");
                    c.userip = GetIP();
                    db.Comments.Add(c);
                    db.SaveChanges();
                    return Content("ok");
                }
                catch (Exception ex)
                {
                    return Content(ex.Message);
                }
            }
            return Content("无权操作");
        }
        //取得用户客户机的IP
        public static string GetIP()
        {
            string IP4Address = String.Empty;


            foreach (IPAddress IPA in Dns.GetHostAddresses(System.Web.HttpContext.Current.Request.UserHostAddress))
            {
                if (IPA.AddressFamily.ToString() == "Internetwork")
                {
                    IP4Address = IPA.ToString();
                    break;
                }
            }

            if (IP4Address != String.Empty)
            {
                return IP4Address;
            }

            foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (IPA.AddressFamily.ToString() == "InterNetwork")
                {
                    IP4Address = IPA.ToString();
                    break;
                }
            }

            return IP4Address;
        }
    }
}