mvc5 webapi 编写
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using SqlSugar; using Models; using WebApplication.Dao; using System.Text; namespace WebApplication.Controllers { /// <summary> /// 分类接口 /// </summary> public class classificationController : ApiController { /// <summary> /// 获取分类列表(条件查询,分页) http://192.168.2.177:1222/api/classification/GetclassificationListPage?pageIndex=1&pageSize=10&status=2&title= /// </summary> /// <param name="pageIndex">分页索引</param> /// <param name="pageSize">分页大小</param> /// <param name="status">状态:0:下线 1:上线 -1:失效,默认传入2获取所有数据</param> /// <param name="title"></param> /// <returns></returns> [Route("api/classification/GetclassificationListPage")] [HttpGet] public string GetclassificationListPage(int pageIndex, int pageSize, int status, string title) { try { using (var db = SugarDao.GetInstance()) { var qable = db.Queryable<tb_classification>(); var dataCountTable = db.Queryable<tb_classification>(); if (status != 2) { qable = qable.Where(i => i.status == status); dataCountTable = dataCountTable.Where(i => i.status == status); } if (status == 2) { dataCountTable = dataCountTable.Where(i => i.status != status); } if (!string.IsNullOrEmpty(title)) { qable = qable.Where(i => i.title.Contains(title)); dataCountTable = dataCountTable.Where(i => i.title.Contains(title)); } var data = qable.OrderBy(it => it.createtime, OrderByType.Asc).ToPageList(pageIndex, pageSize); var dataCount = dataCountTable.ToList().Count; if (data.Count > 0) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据成功", Data = data, Count = dataCount }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据失败", Data = data, Count = dataCount }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "获取数据失败,原因为:" + ex.Message }); } } /// <summary> /// 获取分类数据,不分页 http://192.168.2.177:1222/api/classification/GetclassificationList?status=2&title= /// </summary> /// <param name="status"></param> /// <param name="title"></param> /// <returns></returns> [Route("api/classification/GetclassificationList")] [HttpGet] public string GetclassificationList(int status, string title) { try { using (var db = SugarDao.GetInstance()) { var qable = db.Queryable<tb_classification>(); if (status != 2) { qable = qable.Where(i => i.status == status); } if (!string.IsNullOrEmpty(title)) { qable = qable.Where(i => i.title.Contains(title)); } var data = qable.OrderBy(it => it.createtime, OrderByType.Asc).ToList(); var dataCount = db.Queryable<tb_classification>().Where(it => it.status != status).ToList().Count; if (data.Count > 0) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据成功", Data = data, Count = dataCount }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据失败", Data = data, Count = dataCount }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "获取数据失败,原因为:" + ex.Message }); } } /// <summary> /// 根据id得到对象 http://192.168.2.177:1222/api/classification/GetclassificationModel?id=1 /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("api/classification/GetclassificationModel")] [HttpGet, HttpPost] public string GetclassificationModel(int id) { try { using (var db = SugarDao.GetInstance()) { if (id != 0) { var classification = db.Queryable<tb_classification>().Single(it => it.id == id); if (classification != null) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据成功", Data = classification }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据失败", Data = classification }); } } else { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据失败,无法找到id为:" + id + "的数据", }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "获取数据失败,原因为:" + ex.Message }); } } /// <summary> /// 新增分类 http://192.168.2.177:1222/api/classification/Postclassification /// </summary> /// <param name="classification"></param> [Route("api/classification/Postclassification")] [HttpPost] public string Postclassification(tb_classification classification) { try { classification.createtime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); using (var db = SugarDao.GetInstance()) { object result = db.Insert<tb_classification>(classification); if (Convert.ToInt64(result) > 0) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "添加成功" }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "添加失败" }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "添加失败,原因为:" + ex.Message }); } } /// <summary> /// 修改分类 /// </summary> /// <param name="id"></param> /// <param name="value"></param> [Route("api/classification/Putclassification")] [HttpPost] public string Putclassification(tb_classification classification) { try { classification.createtime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); using (var db = SugarDao.GetInstance()) { bool result = db.Update<tb_classification>(classification, it => it.id == classification.id); if (result == true) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "更新成功" }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "更新失败" }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "更新失败,原因为:" + ex.Message }); } } /// <summary> /// 删除 http://192.168.2.177:1222/api/classification/Deleteclassification?ids=4,5 /// </summary> /// <param name="id"></param> /// <returns></returns> [Route("api/classification/Deleteclassification")] [HttpGet, HttpPost] public string Deleteclassification(string ids) { try { string[] input = ids.Split(','); int[] output = Array.ConvertAll<string, int>(input, delegate (string s) { return int.Parse(s); }); using (var db = SugarDao.GetInstance()) { bool result = db.Delete<tb_classification, int>(output); if (result == true) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "删除成功" }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "删除失败" }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "删除失败,原因为:" + ex.Message }); } } /// <summary> /// 更新状态 http://192.168.2.177:1222/api/classification/UpdateStatus?status=0&ids=2,7 /// </summary> /// <param name="status">状态:0:下线 1:上线 -1:失效 </param> /// <param name="ids"></param> /// <returns></returns> [Route("api/classification/UpdateStatus")] [HttpGet] public string UpdateStatus(int status, string ids) { try { string[] input = ids.Split(','); int[] output = Array.ConvertAll<string, int>(input, delegate (string s) { return int.Parse(s); }); using (var db = SugarDao.GetInstance()) { bool result = db.Update<tb_classification, int>(new { status = status }, output); if (result == true) { return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "状态更改成功" }); } else { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "状态更改失败" }); } } } catch (Exception ex) { return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "状态更改失败,原因为:" + ex.Message }); } } string result = string.Empty; string ChildResult = string.Empty; string temp = string.Empty; /// <summary> /// 分类树形结构 http://192.168.2.177:1222/api/classification/GetclassificationTree /// </summary> /// <returns></returns> [Route("api/classification/GetclassificationTree")] [HttpGet] public string GetclassificationTree() { WebApplication.Controllers.TreeMethod tm = new TreeMethod(); // 找到所有的父节点 List<TreeEntity> treeList1 = tm.findAllParents(); if (treeList1 != null) { for (int i = 0; i < treeList1.Count; i++) { TreeEntity tree = treeList1[i]; // 拼接父节点 //result += "|--" + tree.name; result += "{id:"+tree.id+ ",pId:"+tree.pid+",name:'"+tree.name+"'},"; // 绑定孩子 ChildResult = tm.BindChildByParent(tree.id, "").TrimEnd(','); temp = result + ChildResult; } } else { temp += "没有数据!"; } result = "["+ temp.TrimEnd(',')+ "]"; return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "获取数据成功",Data= temp }); } } public class TreeEntity { public string id { get; set; } public string name { get; set; } public string pid { get; set; } } internal class TreeMethod { /// <summary> /// 找到所有的父节点 /// </summary> /// <returns></returns> public List<TreeEntity> findAllParents() { List<TreeEntity> treeList = new List<TreeEntity>(); using (var db = SugarDao.GetInstance()) { var list = db.Queryable<tb_classification>().Where(it => it.pid == 0 && it.status==1).ToList(); if (list.Count > 0) { for (int i = 0; i < list.Count; i++) { TreeEntity myTree = new TreeEntity(); myTree.id = list[i].id.ToString(); myTree.name = list[i].title; myTree.pid = list[i].pid.ToString(); treeList.Add(myTree); } } } return treeList; } /// <summary> /// 根据父节点找到所有的子节点 /// </summary> /// <param name="pid"></param> /// <returns></returns> public List<TreeEntity> findChildByPid(string pid) { int p_id = Convert.ToInt32(pid); List<TreeEntity> treeList = new List<TreeEntity>(); using (var db = SugarDao.GetInstance()) { var list = db.Queryable<tb_classification>().Where(it => it.pid == p_id&&it.status==1).ToList(); if (list.Count > 0) { for (int i = 0; i < list.Count; i++) { TreeEntity myTree = new TreeEntity(); myTree.id = list[i].id.ToString(); myTree.name = list[i].title; myTree.pid = list[i].pid.ToString(); treeList.Add(myTree); } } } return treeList; } /// <summary> /// 查看是否存在子节点 /// </summary> /// <param name="pid"></param> /// <returns></returns> public bool HasChild(string pid) { int p_id = Convert.ToInt32(pid); int count = 0; bool flag = false; using (var db = SugarDao.GetInstance()) { var list = db.Queryable<tb_classification>().Where(it => it.pid == p_id&it.status==1).ToList(); for (int i = 0; i < list.Count; i++) { count++; } if (count > 0) { flag = true; } } return flag; } string Tree = string.Empty; /// <summary> /// 使用递归拼接父节点的子节点 /// </summary> /// <param name="pid"></param> /// <param name="prefix"></param> public string BindChildByParent(string pid, string prefix) { if (this.HasChild(pid)) { // 得到当前父节点下的所有孩子 List<TreeEntity> list = this.findChildByPid(pid); // 循环拼接当前父节点下的孩子 for (int i = 0; i < list.Count; i++) { //Tree += "|----" + prefix + list[i].name; Tree += "{id:" + list[i].id + ",pId:" + list[i].pid + ",name:'" + list[i].name + "'},"; if (this.HasChild(list[i].id)) { this.BindChildByParent(list[i].id, "--"); } } } return Tree; } } } js调用: <div class="jumbotron"> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p>ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301870">Learn more »</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301871">Learn more »</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301872">Learn more »</a></p> </div> </div> <script src="~/Scripts/jquery-1.10.2.js"></script> <script> $(function () { //var json = "{\"pid\": 0, \"title\": \"123\", \"introduction\":\"321\"}"; //var jsonjson = JSON.parse(json); //$.ajax({ // type: "post", // dataType: "json", // url: " http://192.168.2.177:1222/api/classification/Postclassification", // data:{"str":"jsonjson"}, // success: function (data) { // console.log(data); // } //}); }); function OK() { $.ajax({ type: "post", url: "http://192.168.2.177:1222/api/classification/Postclassification", data: { pid: 1, title: '123哈哈1', introduction:'介绍1'}, success: function (data) { console.log(data); } }); } function update() { $.ajax({ type: "post", url: "http://192.168.2.177:1222/api/classification/Putclassification", data: { id: 11, pid: 1, title: '更新一下', introduction: '更新一下介绍吧' }, success: function (data) { console.log(data); } }); } </script> <div> <h1>新增操作</h1> pid:<input type="text" id="txtPid"/><br /> title:<input type="text" id="txtTitle" /><br /> introduction:<input type="text" id="txtintroduction" /><br /> <input type="button" value="提交" onclick="OK()" /> </div> <div> <h1>修改操作</h1> pid:<input type="text" id="txtPid" /><br /> title:<input type="text" id="txtTitle" /><br /> introduction:<input type="text" id="txtintroduction" /><br /> <input type="button" value="提交" onclick="update()" /> </div>