C# MVC+EF—WebApi
上一篇搭建了页面,这里写下功能。
这里我用WebApi实现数据的增删改查。
一、新建Controller
为了区分明确,我在Controller文件夹下建立一个WebApi文件夹存放。
选中文件夹右键单击=》添加=》控制器=》Web Api控制器
1、这样会自动生成一个控制器,继承ApiController类
namespace mvc.Controllers.WebApi
{
public class DepartmentController : ApiController
{ }
}
2、在App_Start文件夹下会自动生成WebApiConfig文件,这个文件的功能是定义WebApi的路由,WebApi路由是单独控制的
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
3、路由是可以自定义的,不一定要按照默认的规则,可以根据自己的需要调整路由规则。
为了区分更明确,我在默认路由的基础上增加一个action
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
4、在Global.asax文件的Application_Start方法下注册WebApi路由,如果不注册是路由规则是不生效的。
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
二、为了使用方便新建一些辅助类
在models文件夹下,新增PageQuery文件夹存放
1、记录返回值
public class APIResult
{
public APIResult()
{
message = "请求失败";
} public bool success { get; set; }
public string message { get; set; }
public int code { get; set; }
public object data { get; set; }
}
2、查询基类
public class QueryBase
{
public int page { get; set; }
public int rows { get; set; }
}
3、查询类,继承查询基类
public class DepartmentQuery: QueryBase
{
/// <summary>
/// 部门名称
/// </summary>
public string Name { get; set; }
}
三、实现功能
一般请求方式是这样区分的: Post:新增记录;Put:修改记录;Get:获取数据;Delete:删除数据
namespace mvc.Controllers.WebApi
{
public class DepartmentController : ApiController
{
/// <summary>
/// 查询部门信息
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
[HttpPost]
public IHttpActionResult Pager(DepartmentQuery query)
{
List<Department> deplist = new List<Department>();
int total = ;
using (var context = new DBContext.PracticeContext())
{
var querylist = context.Department.AsQueryable();
if (!string.IsNullOrEmpty(query.Name))
{
querylist = querylist.Where(s => s.Name.Contains(query.Name));
}
querylist = querylist.Where(s => s.IsDel == false);
total = querylist.Count();
var result = querylist.OrderByDescending(s => s.OrderId).Skip(query.rows * (query.page - )).Take(query.rows);
deplist = result.ToList();
return Ok(new APIResult()
{
success = true,
message = "请求成功",
data = deplist
});
}
}
/// <summary>
/// 新增部门信息
/// </summary>
/// <param name="dep">部门model</param>
/// <returns></returns>
[HttpPost]
public IHttpActionResult Create(Department dep)
{
using (var context = new DBContext.PracticeContext())
{
Department department = new Department
{
Name = dep.Name,
Introduce = dep.Introduce,
OrderId = dep.OrderId,
IsShow = dep.IsShow
};
context.Department.Add(department);
context.SaveChanges();
return Ok(new APIResult()
{
success = true,
data = department,
message = "新增成功"
});
}
}
/// <summary>
/// 修改部门信息
/// </summary>
/// <param name="dep">部门model</param>
/// <returns></returns>
[HttpPut]
public IHttpActionResult Update(int id, Department dep)
{
using (var context = new DBContext.PracticeContext())
{
Department department = context.Department.Find(id);
if (department != null)
{
department.Name = dep.Name;
department.Introduce = dep.Introduce;
department.OrderId = dep.OrderId;
department.IsShow = dep.IsShow;
}
context.SaveChanges();
return Ok(new APIResult()
{
success = true,
data = department,
message = "更新成功"
});
}
}
/// <summary>
/// 删除部门
/// </summary>
/// <param name="id">Id</param>
/// <returns></returns>
[HttpDelete]
public IHttpActionResult Delete(int id)
{
using (var context = new DBContext.PracticeContext())
{
Department department = context.Department.Find(id);
if (department != null)
{
department.IsDel = true;
}
context.SaveChanges(); return Ok(new APIResult()
{
success = true,
message = "删除成功"
});
}
}
}
}
四、调用WebApi接口
1、在控制器中新建Add方法
public class DepartmentController : Controller
{
// GET: Department
public ActionResult Index()
{
return View();
}
public ActionResult Add()
{
return View();
}
}
2、 光标定在Add方法上右键单击=》添加视图
3、添加表单
@model mvc.Models.Department @{
ViewBag.Title = "Edit";
Layout = null;
} <div class="wrapper">
<div class="easyui-panel" title="部门添加" style="width:30%;height:100%">
<form id="ff">
<table style="border-collapse:separate; border-spacing:10px;">
<tr>
<td>部门名称:</td>
<td>
@Html.TextBoxFor(s => s.Name, new { @class = "easyui-textbox", style = "width:300px" })
</td>
</tr>
<tr>
<td>介绍:</td>
<td>
@Html.TextBoxFor(s => s.Introduce, new { @class = "easyui-textbox", style = "width:100%", @data_options = "multiline:true,height:80" })
</td>
</tr>
<tr>
<td>排序值:</td>
<td>
@Html.TextBoxFor(s => s.OrderId, new { @class = "easyui-numberspinner", style = "width:100%", data_options = "min:1,max:100,required:true" })
</td>
</tr>
<tr>
<td> 是否显示:</td>
<td>
<input id="IsShow" class="easyui-switchbutton" data-options="onText:'是',offText:'否'">
</td>
</tr>
<tr>
<td></td>
<td>
<a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()">保存</a>
</td>
</tr>
</table>
</form>
</div>
</div> <script src="~/WebPlugins/EasyUI/jquery.min.js"></script>
<script src="~/WebPlugins/EasyUI/jquery.easyui.min.js"></script>
<link href="~/WebPlugins/EasyUI/themes/default/easyui.css" rel="stylesheet" /> <script type="text/javascript">
function submitForm() {
$.ajax({
url: '/api/department/create',
method: "POST",
data: $('form').serialize(),
dataType: 'json',
success: function (data) {
var result = eval(data);
if (result["success"]) {
alert("添加成功!");
}
}
})
}
</script>
4、点击确定之后表单中的数据就添加进数据库了。
C# MVC+EF—WebApi的更多相关文章
- Asp.Net MVC EF各版本区别
2009年發行ASP.NET MVC 1.0版 2010年發行ASP.NET MVC 2.0版,VS2010 2011年發行ASP.NET MVC 3.0版+EF4,需要.Net4.0支持,VS2 ...
- SlickOne -- 基于Dapper, Mvc和WebAPI 的快速开发框架
前言:在两年前,项目组推出了基于Dapper,Mvc和WebApi的快速开发框架,随着后续Slickflow产品的实践和应用,今再次对SlickOne项目做以回顾和总结.其目的是精简,持续改进,保持重 ...
- SQLSERVER 数据库性能的的基本 MVC + EF + Bootstrap 2 权限管理
SQLSERVER 数据库性能的基本 很久没有写文章了,在系统正式上线之前,DBA一般都要测试一下服务器的性能 比如你有很多的服务器,有些做web服务器,有些做缓存服务器,有些做文件服务器,有些做数据 ...
- [转帖]Asp.Net MVC EF各版本区别
Asp.Net MVC EF各版本区别 https://www.cnblogs.com/liangxiaofeng/p/5840754.html 2009年發行ASP.NET MVC 1.0版 201 ...
- SlickOne敏捷开发框架介绍(一) -- 基于Dapper, Mvc和WebAPI 的快速开发框架
前言:在两年前(最初发布时间:2013年1月9日(csdn),当前文章时间2015年11月10日),项目组推出了基于Dapper,Mvc和WebApi的快速开发框架,随着后续Slickflow产品的实 ...
- [转]Asp.Net MVC EF各版本区别
本文转自:http://www.cnblogs.com/liangxiaofeng/p/5840754.html 2009年發行ASP.NET MVC 1.0版 2010年發行ASP.NET MVC ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列(24)-权限组的设计和实现(附源码)(终结)
ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) (1):框架搭建 (2):数据库访问层的设计Demo (3):面向接口编程 (4 ):业务逻辑层的封装 ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列(23)-设置角色遗留问题和为权限设置角色以及EasyUI Tabs的使用
ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) (1):框架搭建 (2):数据库访问层的设计Demo (3):面向接口编程 (4 ):业务逻辑层的封装 ...
- ASP.NET MVC+EF框架+EasyUI实现权限管理系列(22)-为用户设置角色
ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) (1):框架搭建 (2):数据库访问层的设计Demo (3):面向接口编程 (4 ):业务逻辑层的封装 ...
随机推荐
- hash bucket
什么是bucket bucket的英文解释: Hash table lookup operations are often O(n/m) (where n is the number of objec ...
- 快速准备(复制替换)一套新测试环境,CentOS7 MySQL相关配置
拿到一个新环境,需要找相关配置,我有一个办法,相对能比较快速地复制一套环境出来. 修改机器配置: virsh 相关几条命令,已完成,后续我再整理补充... 虚拟化相关,参考:https://www.c ...
- 利用fstream进行文件拷贝测试
今天翻到一个早期写测试代码的目录,找到几个以前的测试代码,于是拿出来贴到博客中.(只是简单的测试,并不严谨.注意这里windows和linux的硬件环境不一样) 这一个是使用fstream进行文件拷贝 ...
- GitHub下载安装以及开源项目
Git for Windows安装与使用 http://cioworld.org/freedom/content/git-windows 下载Git-1.8.3-preview20130601.exe ...
- 带参数的sigmoid
$y=\frac{1}{1+e^{-(\alpha\times x+\beta)}}$ alpha越大,曲线越陡峭,beta控制平移 import numpy as np import pylab a ...
- ASCII、Unicode和UTF-8编码的区别
归纳: 编码 大小 支持语言 ASCII 1个字节 英文 Unicode 2个字节(生僻字4个) 所有语言 UTF-8 1-6个字节,英文字母1个字节,汉字3个字节,生僻字4-6个字节 所有语言 具体 ...
- 详解nginx 配置多个tomcat共用80端口
场景:项目1放在tomcat1中,项目2放在tomcat2中,两个tomcat放在同一台服务器上,需要共享80端口访问注意:这里和集群部署是不同的,集群部署是一个项目放在多个tomcat中.这里通过n ...
- FragmentPagerAdapter 与 FragmentStatePagerAdapter 的区别
参考链接: http://blog.csdn.net/dreamzml/article/details/9951577 简单来说前者适合静态.少量的Fragment 后者适合动态.较多的Fragmen ...
- Google file system
读完了Google file system论文的中文版,记录一下总结,懒得打字,直接上草图:
- oracle结合mybatis批量插入数据
先上代码: controller: result = service.insertTRbXdhjLendYdData(params); service: List<TRbXdhjLendDTO& ...