首页 > 编程语言 >C# webAPI +access+xadmin+layui 前端

C# webAPI +access+xadmin+layui 前端

时间:2022-10-28 17:04:33浏览次数:63  
标签:webAPI xadmin C# System int resultMsg new using public


1. 首先创建webAPI项目:

C# webAPI +access+xadmin+layui 前端_C# access

 2. 创建DAL类库,用户访问数据库。

添加AccessHelper 封装一个数据库访问类:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
public static class AccessHelper
{

private static string connstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\Users\\hcy\\Documents\\TextBook.mdb";
public static DataTable GetDataTableBySql(string sql)
{
OleDbConnection conn = new OleDbConnection(connstr); //Jet OLEDB:Database Password=
OleDbCommand cmd = conn.CreateCommand();

cmd.CommandText = sql; // "select * from books";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
if (dr.HasRows)
{
for (int i = 0; i < dr.FieldCount; i++)
{
dt.Columns.Add(dr.GetName(i));
}
dt.Rows.Clear();
}
while (dr.Read())
{
DataRow row = dt.NewRow();
for (int i = 0; i < dr.FieldCount; i++)
{
row[i] = dr[i];
}
dt.Rows.Add(row);
}
cmd.Dispose();
conn.Close();
return dt;
}

public static int ExecuteNonQuerySql(string sql) {
int rows = 0;

using (OleDbConnection connect = new OleDbConnection(connstr))
{
using (OleDbCommand cmd = new OleDbCommand(sql, connect))
{
//if (para != null && para.Length > 0)
// cmd.Parameters.AddRange(para);
if (connect.State == System.Data.ConnectionState.Closed) connect.Open();

rows = cmd.ExecuteNonQuery();
}
}
return rows;
}
}
}

3. 添加一个控制器 用于存放数据

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace SchoolWorkAPI.Controllers
{
[RoutePrefix("api/TextBooks")]
public class TextBooksController : ApiController
{
[HttpGet]
[Route("test")]
public IHttpActionResult Get()
{


//string sqlSelect = "select count(*) from EmpInfo";
//object count = DAL.SqlHelper.ExecuteScalar(DAL.SqlHelper.Connstr, CommandType.Text, sqlSelect, null);
return Ok("API OK, and result empCount:" + 0);

}

[HttpPost]
[Route("getBooksList")]
public HttpResponseMessage getBooksList([FromBody] PageHelper pageHelper)
{
ResultMsg resultMsg = new ResultMsg();

string sqlTotal = "select * from books";
DataTable dt_totals = DAL.AccessHelper.GetDataTableBySql(sqlTotal);

// string sql = string.Format("select top 10 * from books where id not in (select top " + pageHelper.Page * 10 + " id from books order by id desc ) order by id desc");

string sql= "SELECT * FROM (SELECT TOP "+pageHelper.Rows+" * FROM(SELECT TOP "+
pageHelper.Page*pageHelper.Rows+" * FROM books ORDER BY id DESC) ORDER BY id) ORDER BY id DESC ";


DataTable dt = DAL.AccessHelper.GetDataTableBySql(sql);
ResultDataInfo resultDataInfo = new ResultDataInfo();
resultDataInfo.data = DAL.DataTableTo.ToDataList<Models.TextBooksInfo>(dt);
resultDataInfo.total = dt_totals.Rows.Count;
resultMsg.data = resultDataInfo;
resultMsg.code = ResultMsgCode.SUCCESS;
resultMsg.msg = "success";
return toJson(resultMsg);
}


[HttpPost]
[Route("add")]
public HttpResponseMessage addBooksList([FromBody] Models.TextBooksInfo info)
{
ResultMsg resultMsg = new ResultMsg();
string sql = "select * from books";
int result = DAL.AccessHelper.ExecuteNonQuerySql(sql);
resultMsg.data = result;
resultMsg.code = ResultMsgCode.SUCCESS;
resultMsg.msg = "success";
return toJson(resultMsg);
}

[HttpPost]
[Route("update")]
public HttpResponseMessage updateBooksList([FromBody] Models.TextBooksInfo info)
{
ResultMsg resultMsg = new ResultMsg();
string sql = "select * from books";
int result = DAL.AccessHelper.ExecuteNonQuerySql(sql);
resultMsg.data = result;
resultMsg.code = ResultMsgCode.SUCCESS;
resultMsg.msg = "success";
return toJson(resultMsg);
}

[HttpPost]
[Route("del")]
public HttpResponseMessage delBooksList([FromBody] Models.TextBooksInfo info)
{
ResultMsg resultMsg = new ResultMsg();
string sql = "select * from books";
int result = DAL.AccessHelper.ExecuteNonQuerySql(sql);
resultMsg.data = result;
resultMsg.code = ResultMsgCode.SUCCESS;
resultMsg.msg = "success";
return toJson(resultMsg);
}


public static HttpResponseMessage toJson(Object obj)
{
String str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
//serializer.RegisterConverters(new JavaScriptConverter[]{new DataTableConverter()});
str = serializer.Serialize(obj);
}
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}

public static HttpResponseMessage toJson2(DataTable dt) {
String str=DataTableToJson(dt);//
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}

public static string DataTableToJson(DataTable table)
{
StringBuilder JsonString = new StringBuilder();
if (table.Rows.Count > 0)
{
JsonString.Append("[");
for (int i = 0; i < table.Rows.Count; i++)
{
JsonString.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
if (j < table.Columns.Count - 1)
{
JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
}
else if (j == table.Columns.Count - 1)
{
JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
}
}
if (i == table.Rows.Count - 1)
{
JsonString.Append("}");
}
else
{
JsonString.Append("},");
}
}
JsonString.Append("]");
}
return JsonString.ToString();
}
}

public class PostDataInfo
{
private object data;
private string type;

public object Data { get => data; set => data = value; }
public string Type { get => type; set => type = value; }
}

public class ResultMsg
{
public int code { get; set; }
public Object data { get; set; }
public object msg { get; set; }
}
public class ResultMsgCode
{
/// <summary>
/// 成功
/// </summary>
public static int SUCCESS = 200;
/// <summary>
/// 失败
/// </summary>
public static int ERR = 201;
}

public class PageHelper {

private int page;
private int rows;

public int Page { get => page; set => page = value; }
public int Rows { get => rows; set => rows = value; }
}

public class ResultDataInfo {
public int total { get; set; }
public IList data { get; set; }
}

}

几个类方法等介绍:

HttpResponseMessage 指定返回类型

ResultMsg  指定返回数据的框架在这个之内返回,便于前端数据对接

ResultDataInfo 返回数据的具体承载类

3. 前端采用 layui 加分页 和Xadmin框架对数据展示

。。。。未完待续

标签:webAPI,xadmin,C#,System,int,resultMsg,new,using,public
From: https://blog.51cto.com/51souta/5805155

相关文章

  • 通过抹黑java等其他语言提升C# 存在感?NO NO
    今天在写业务的时候突然看到了以前封装的java库里关于java时间格式化的代码。感觉到了深深的恶意感。来一起看下java的: 还有一个合并后后的再来看一个golang的 Golang格......
  • C# UpdClient 发送16进制
    C#如何发送已知"77852563821574"这样的16进制?publicstaticbyte[]HexStringToBytes(stringhs){string[]strArr=hs.Trim(......
  • MHATC系统笔记2
    Tip:1、修改FDO.jar解决导入长期计划时,如果航路为空导入不成功问题;原来的代码是有条件删除长期计划历史库中的数据,导致从长期计划向长期计划历史库中转存数据时两个表中存在......
  • 问题定位记录1:Djano-redis库报错No connection available
    一、问题现象MANO(网络管理与编排软件)原子层创建资源后写redis缓存时报错Noconnectionavaiable堆栈打印:Traceback(mostrecentcalllast): File"/home/oes/.loca......
  • Flutter开发之Scaffold组件快速开发APP
    Scaffold包括的属性constScaffold({Key?key,PreferredSizeWidget?appBar,Widget?body,Widget?floatingActionButton,FloatingActionButtonLocation?floatingAct......
  • 智能分析网关使用教程:如何在EasyCVR视频融合平台配置告警与抓拍?
    AI智能分析网关设备内置多种深度学习算法,可支持对接入的多路视频流进行智能检测、智能识别等,包括人脸检测与识别、车辆检测与识别、车牌识别、烟火识别、安全帽识别、区域入......
  • AI车辆识别视频融合平台EasyCVR告警预案如何关联国标通道?
    在前期的文章中我们介绍了关于EasyCVR平台新增的告警预案功能及开发流程,今天我们来分享一下如何将告警预案关联国标通道。告警预案可以根据告警类型、告警级别、告警方式、......
  • centos7安装gitlab
    centos7安装gitlabgitlab下载地址 https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el7/gitlab-ce-12.7.8-ce.0.el7.x86_64.rpm 1、安装相关依赖yum-yinstal......
  • app.config ConfigurationHelper
    usingSystem;usingSystem.Configuration;namespaceEncryptTool{///<summary>///用于XML操作///</summary>publicclassConfigurationHelp......
  • 前端docx文件阅览
    1.下载npminstall docx-preview-S 2.<el-button@click="lookDocx">文件阅览</el-button><divclass="docWrap"><divref="file"></div>......