ajax通過forEach循環遍歷json數據並通過js模板字符串獲取數據,后台使用ef mvc 三層
html代碼:
<div class="text-center"> <form id="form1" method="post" action="/Movies/GetAllByArea"> <h2>電影排行榜</h2> <select id="Area" name="Area" onchange="GetMovieByArea()" class="form-control"> <option value="" selected>所有</option> @foreach (var item in arealist) { <option value="@item.Area">@item.Area</option> } </select> </form> </div> <table class="table"> <tr> <td>電影排名</td> <td>電影名稱</td> <td>上映時間</td> <td>電影畫報</td> <td>所屬國家</td> <td>電影評分</td> <td>操作</td> </tr> <tbody id="tb"> @foreach (var item in Model) { <tr> <td>@item.MoviesID</td> <td>@item.MovieName</td> <td> <img src="~/Images/@item.Image" style="height:66px;width:50px;"/> </td> <td>@item.ReleaseTime</td> <td>@item.Area</td> <td>@item.Rating</td> <td> <a href="/Movies/Delete?MovieId=@item.MoviesID" onclick="return confirm('你確定要刪除這條數據嗎?')">刪除</a> </td> </tr> } </tbody> </table>
后台json數據處理:
public JsonResult GetAllByArea(string area) { List<RankingList> rankingLists = rankingListBLL.GetRankingLists(area); return Json(new { data= rankingLists }); }
ajax處理根據條件查詢:
<script> function GetMovieByArea() { $.ajax({ type: "post", url: "/Movies/GetAllByArea", data: { Area: $("#Area").find("option:selected").val() }, success: function (msg) { console.log(msg); var arr = msg.data; let htmldata = ""; arr.forEach(function (item) {
item.AddTime = new Date(parseInt('/Date(1593671071513)/'.substr(6, 13))).toLocaleString();//時間轉換2020/7/2 下午2:24:31 htmldata+=` <tr> <td> ${item.MoviesID} </td> <td> ${item.MovieName} </td> <td> ${item.ReleaseTime}</td> <td> <img src="/Images/${item.Image}" style="height:70px;width:56px;"/> </td> <td> ${item.Area} </td> <td> ${item.Rating} </td> <td> <a href="/Movies/Delete?MovieId=${item.MoviesID}">刪除</a> </td> </tr> ` }) $("#tb").html(htmldata); } }) } </script>
后台封裝Dto層:
public List<LogisticsDto> GetAllLogistics(string code,string states) { _db.Configuration.ProxyCreationEnabled = false; return _db.Logistics .Where(m=>string.IsNullOrEmpty(states)&string.IsNullOrEmpty(code) || m.State.Contains(states)&m.Code.Contains(code)) .Select(m=>new LogisticsDto() { Id=m.Id, Code=m.Code, State=m.States.StateName, Desc=m.Desc, AddTime= (DateTime)m.AddTime }) .ToList(); }