排球计分程序重构(下篇)

 public ActionResult Scores(long page, long limit)
        {
            PetaPoco.Page<CompetitionScore> list = CompetitionScore.Page(page, limit, "select * from CompetitionScore");
            Data data = new Data();
            data.count = list.TotalItems;
            data.data = new List<dynamic>();
            foreach (var item in list.Items)
            {
                string homeTeamName = Team.FirstOrDefault("where Id=" + item.HomeTeamId + "").TeamName;
                string guestTeamName = Team.FirstOrDefault("where Id=" + item.GuestTeamId + "").TeamName;
                string theScore = item.HomeTeamScore.ToString() + "" + item.GuestTeamScore.ToString();
                data.data.Add(new { HomeTeanName = homeTeamName, GuestTeamName = guestTeamName, Id = item.Id, TheScore = theScore });
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        } 

先以这块代码为例在Return中返回Json格式的数据,以便前端能够动态加载表格。

Data中data是一个匿名类型的集合,也就是说无论哪一个模型类,都可以通过这种方式给他转换成一个匿名类并转换为Json格式的数据给传到前台显示。

@{
    ViewBag.Title = "添加队伍";
}
@using (Ajax.BeginForm(new AjaxOptions {
    Url= "/Teams/AddTeam",
    HttpMethod = "Post",
    OnSuccess = "success",
    OnBegin = ""
}))
{
    <div class="layui-form" style="width:100%;height:300px;">
        <div style="margin-left:35%; margin-bottom:30px;margin-top:10px;" ><img class="layui-anim layui-anim-fadein layui-anim-rotate " src="~/Content/Image/rabbit.gif"/></div>
        <div class="layui-form-item">
            <label class="layui-form-label">队名</label>
            <div class="layui-input-block">
                <input type="text" name="teamName" id="teamName" placeholder="请输入队名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block" style="text-align:center;">
                <input type="submit" class="layui-btn" id="btn" value="立即提交" />
            </div>
        </div>
    </div>
}
<script>
    function success(data) {
        if (data == "添加成功") {
            layer.msg(data, { icon: 1 });
            setTimeout("window.location = '/Teams/GetTeams'", 2000);
        }
        else {
            layer.msg(data, { icon: 2 });
        }
    }
</script>

 

在这段代码中使用了MVC自带的自动生成表格,并且做了一个异步的表格提交,表格以Post方式提交,在Action中进行处理

[HttpPost]
        public ActionResult AddTeam(string teamName)
        {
            string msg = "";
            if (teamName == "" || teamName == null)
            {
                msg = "请输入队名";
            }
            else
            {
                Team team = new Team();
                team.TeamName = teamName;
                db.Insert(team);
                msg = "添加成功";
            }
            return Json(msg);
        } 

还有其他的一些异步处理的方法。比如在计分控制器中,很多地方用到,前端判断比赛是否一局比赛结束,结束就进行异步添加一条记录等等。

 

posted @ 2017-09-10 00:42  colorful丶  阅读(167)  评论(0编辑  收藏  举报