admin 管理员组

文章数量: 1086864

220429

-----API控制器-----

        //列表显示
        [HttpGet]
        public List<TeacherDto> TeacherListGet()
        {
            using (var db = new TeacherDBEntity())
            {
                var list = db.Teacher.Select(s => new TeacherDto()
                {
                    Id = s.Id,
                    AvgScore = s.AvgScore,
                    ClassHour = s.ClassHour,
                    Course = s.Course,
                    Department = s.Department,
                    Name = s.Name,
                    Sex = s.Sex
                }).ToList();
                return list;
            }
        }

        //添加
        [HttpPost]
        public AjaxResult AddPost(int id, [FromBody] ScoreInfoDto dto)
        {
            using (var db = new TeacherDBEntity())
            {
                var tmodel = db.Teacher.FirstOrDefault(s => s.Id == id);
                var model = new ScoreInfo()
                {
                    AddTime = DateTime.Now,
                    Comment = dto.Comment,
                    Score = dto.Score,
                    TeacherId = tmodel.Id
                };
                var score = db.ScoreInfo.Where(s => s.TeacherId == id).Select(s => s.Score).DefaultIfEmpty().Sum();
                var scount = db.ScoreInfo.Where(s => s.TeacherId == id).Select(s => s.Score).Count();
                if (score == 0)
                {
                    tmodel.AvgScore = dto.Score;
                }
                else
                {
                    tmodel.AvgScore = Convert.ToDouble((score + dto.Score) / (scount + 1));
                }
                db.ScoreInfo.Add(model);
                int i = db.SaveChanges();
                if (i > 0)
                {
                    return new AjaxResult() { State = 1, Message = "添加成功" };
                }
                else
                {
                    return new AjaxResult() { State = -1, Message = "添加失败" };
                }
            }
        }

        //获取修改信息
        [HttpGet]
        public EditDto TeacherByIDGet(int id)
        {
            using (var db = new TeacherDBEntity())
            {
                var model = db.Teacher.FirstOrDefault(s => s.Id == id);
                var dto = new EditDto()
                {
                    ClassHour = model.ClassHour,
                    Course = model.Course,
                    Department = model.Department,
                    Name = model.Name,
                    Sex = model.Sex
                };
                return dto;
            }
        }

        //修改
        [HttpPut]
        public AjaxResult Put(int id, [FromBody] EditDto dto)
        {
            using (var db = new TeacherDBEntity())
            {
                var model = db.Teacher.FirstOrDefault(s => s.Id == id);
                model.Course = dto.Course;
                model.Department = dto.Department;
                model.Name = dto.Name;
                model.Sex = dto.Sex;
                model.ClassHour = dto.ClassHour;
                int i = db.SaveChanges();
                if (i > 0)
                {
                    return new AjaxResult() { State = 1, Message = "更新成功" };
                }
                else
                {
                    return new AjaxResult() { State = -1, Message = "更新失败" };
                }
            }
        }

        //查看评价
        [Route("api/values/{id}")]
        [HttpGet]
        public List<ScoreCKDto> ChaKanGet(int id)
        {
            using (var db = new TeacherDBEntity())
            {
                var model = db.Teacher.FirstOrDefault(s => s.Id == id);
                var list = db.ScoreInfo.Where(w => w.TeacherId == id).Select(s => new ScoreCKDto()
                {
                    AddTime = s.AddTime,
                    Comment = s.Comment,
                    Score = s.Score,
                    Name = model.Name
                }).ToList();
                return list;
            }
        }

-----MVC控制器-----

(int id)
ViewBag.id = id;

-----WebAPI配置和服务-----

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));     //三个*表示本服务支持任意请求来访问
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

-----列表-----

<table class="table table-bordered table-hover">
    <tr>
        <th>课程</th>
        <th>院系</th>
        <th>姓名</th>
        <th>性别</th>
        <th>课时</th>
        <th>平均分</th>
        <th>操作</th>
    </tr>
</table>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
    $(function () {
        $.ajax({
            url: "http://localhost:62629/api/teacherapi",
            type: "get",
            data: {},
            dataType: "json",
            success: function (r) {
                console.log(r);
                var str = "";
                $.each(r, function (index, row) {
                    str += "<tr>";
                    str += "<td>" + row.Course + "</td>";
                    str += "<td>" + row.Department + "</td>";
                    str += "<td>" + row.Name + "</td>";
                    str += "<td>" + (row.Sex ? "男" : "女") + "</td>";
                    str += "<td>" + row.ClassHour + "</td>";
                    str += "<td>" + row.AvgScore + "</td>";
                    str += '<td><a href="/Teachermvc/Edit/' + row.Id + '" class="btn btn-success ">编辑信息</a>' +
                        ' <a href="/Teachermvc/CKIndex/' + row.Id + '" class="btn btn-warning  ">查看评价</a>' +
                        ' <a href="/Teachermvc/Add/' + row.Id + '" class="btn btn-info ">添加评价</a></td>';
                    str += "</tr>";
                });
                $(".table").append(str);
            }
        })
    })
</script>

-----添加-----

<table class="table table-bordered">
    <tr>
        <td>评分</td>
        <td><input type="text" id="Score" class="form-control" /></td>
    </tr>
    <tr>
        <td>评语</td>
        <td><textarea id="Comment" rows="3" class="form-control "></textarea></td>
    </tr>
    <tr>
        <td colspan="2"><input type="button" name="" value="立即提交" class="btn btn-success " οnclick="Add()" /></td>
    </tr>
</table>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
    function Add() {
        $.ajax({
            url: "http://localhost:62629/api/teacherapi/"+@ViewBag.id,
            type: "post",
            data: {
                "Score": $("#Score").val(),
                "Comment": $("#Comment").val()
                },
            dataType: "json",
            success: function (r) {
                console.log(r);
                alert(r.Message);
                if (r.State==1) {
                    location.href = "/Teachermvc/Index";
                }
            }
        })
    }
</script>

-----修改-----

<table class="table table-bordered table-hover ">
    <tr>
        <td>课程</td>
        <td><input type="text" id="Course" class="form-control" /></td>
    </tr>
    <tr>
        <td>院系</td>
        <td><input type="text" id="Department" class="form-control" /></td>
    </tr>
    <tr>
        <td>姓名</td>
        <td><input type="text" id="Name" class="form-control" /></td>
    </tr>
    <tr>
        <td>性别</td>
        <td>
            <select id="Sex" class="form-control">
                <option value="true">男</option>
                <option value="false">女</option>
            </select>
        </td>
    </tr>
    <tr>
        <td>课时</td>
        <td><input type="text" id="ClassHour" class="form-control" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="button" name="" value="立即提交" class="btn btn-success " οnclick="Edit()" />
        </td>
    </tr>
</table>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
    $(function () {
        $.ajax({
            url: "http://localhost:62629/api/teacherapi/"+@ViewBag.id,
            type: "get",
            data: {},
            dataType: "json",
            success: function (r) {
                console.log(r);
                $("#Course").val(r.Course);
                $("#Department").val(r.Department);
                $("#Name").val(r.Name);
                if (r.Sex)
                {
                    $("#Sex option:first").prop("selected", "selected");
                }
                else
                {
                    $("#Sex option:last").prop("selected", "selected");
                }
                $("#ClassHour").val(r.ClassHour);
                $("#AvgScore").val(r.AvgScore);
            }
        })
    })

    function Edit() {
        $.ajax({
            url: "http://localhost:62629/api/teacherapi/"+@ViewBag.id,
            type: "put",
            data: {
              "Course" : $("#Course").val(),
               "Department": $("#Department").val(),
              "Name" : $("#Name").val(),
              "Sex" :$("input[name='Sex']:checked").val(),
              "ClassHour" : $("#ClassHour").val(),
              "AvgScore" :$("#AvgScore").val()
            },
            dataType: "json",
            success: function (r) {
                console.log(r);
                alert(r.Message);
                if (r.State = 1) {
                    location.href = "/Teachermvc/Index";
                }
            }
        })
    }
</script>

-----查看-----

<table class="table table-bordered  table-hover ">
    <tr>
        <th>姓名</th>
        <th>评分</th>
        <th>评语</th>
        <th>日期</th>
    </tr>
</table>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
    //json日期格式转换为正常格式
    function jsonDateFormat(jsonDate) {
        try {
            var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        } catch (ex) {
            return "";
        }
    }
    $(function () {
        $.ajax({
            url: "http://localhost:62629/api/values/"+@ViewBag.id,
            type: "get",
            data: {},
            dataType: "json",
            success: function (r) {
                console.log(r);
                var str = "";
                $.each(r, function (index, row) {
                    str += "<tr>";
                    str += "<td>" + row.Name + "</td>";
                    str += "<td>" + row.Score + "</td>";
                    str += "<td>" + row.Comment + "</td>";
                    str += "<td>" + jsonDateFormat(row.AddTime) + "</td>";
                    str += "</tr>";
                });
                $(".table").append(str);
            }
        })
    })
</script>

本文标签: 220429