//显示 public DataTable ExecTable(string sql) { DataSet set = new DataSet(); using (SqlConnection conn = new SqlConnection(con)) { conn.Open(); using (SqlCommand comm = new SqlCommand(sql,conn)) { SqlDataAdapter adapter = new SqlDataAdapter(comm); adapter.Fill(set); } } return set.Tables[0]; } //增删改 public int ExecNounQuery(string sql) { int flag = 0; using (SqlConnection conn = new SqlConnection(con)) { conn.Open(); using (SqlCommand comm = new SqlCommand(sql, conn)) { flag = comm.ExecuteNonQuery(); } } return flag; }
DBHelper db = new DBHelper(); //显示 public DataTable GetShow() { string sql = "select * from ProductTB p join ProductType t on p.TID=t.TID"; return db.ExecTable(sql); } //添加 public int GetAdd(RoweModel m) { string sql = $"insert into ProductTB values(‘{m.PName}‘,‘{m.Price}‘,‘{m.State}‘,‘{m.TID}‘)"; return db.ExecNounQuery(sql); }
RoweBLL bll = new RoweBLL(); //显示 [HttpGet] [Route("api/GetShow")] public IHttpActionResult GetShow(string name = "") { DataTable tb = bll.GetShow(); string json = JsonConvert.SerializeObject(tb); List<RoweModel> list = JsonConvert.DeserializeObject<List<RoweModel>>(json); var list1 = (from s in list select s).ToList(); if (!string.IsNullOrEmpty(name)) { list1 = list1.Where(s => s.PName.Contains(name)).ToList(); } return Json<List<RoweModel>>(list1); } //添加 [HttpPost] public int GetAdd(RoweModel m) { int flag = bll.GetAdd(m); return flag; }
<script> $(function () { Show(); }); //显示 function Show() { $.ajax({ url: "http://localhost:58473/api/GetShow", type: "get", dataType: "json", }).done(function (da) { ShowList(da); }); } function ShowList(da) { //清空 $("#tb").empty(); $.each(da, function (index, item) { var str = "<tr>" + "<td>" + item.ID + "</td>" + "<td>" + item.PName + "</td>" + "<td>" + item.TName + "</td>" + "<td>" + item.Price + "</td>" + "<td>" + item.State + "</td>" + "</tr>"; $("#tb").append(str); }) } </script>