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 ):业务逻辑层的封装 ...
随机推荐
- [JS]两个常用的取随机整数的函数
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...
- 【ZH奶酪】如何用Python实现编辑距离?
1. 什么是编辑距离? 编辑距离(Edit Distance),又称Levenshtein距离,是指两个字串之间,由一个转成另一个所需的最少编辑操作次数.许可的编辑操作包括将一个字符替换成另一个字符, ...
- python module install
1.issue: How can I bypass kivy module error: ImportError: DLL load failed: The specified module coul ...
- 9.11 翻译系列:数据注解特性之--Timestamp【EF 6 Code-First系列】
原文链接:https://www.entityframeworktutorial.net/code-first/TimeStamp-dataannotations-attribute-in-code- ...
- netty实现多个handler顺序调用
在netty中,一次数据交互,可以由多个handler去处理,例如 handler1 和 handler2,那么,在前面那个handler的 messageReceived 的最后要加上 ctx.se ...
- windows下安装pycharm并连接Linux的python环境
1. 下载安装Pycharm专业版 具体方法略.Pycharm5激活方法参考http://www.cnblogs.com/snsdzjlz320/p/7110186.html 2. 添加配置连接远程服 ...
- 将png图片转换为字体图标
字体图标不仅可以随意调整大小,而且可以避免在页面制作过程中引用N多的图片,发送请求造成的流量浪费,因此,我们可以将图标的icon转换成字体图标: 方法一: 1.将png格式的图片转换成svg格式: 网 ...
- Ubuntu下的Wine&WineQQ
一.安装Wine 1.添加PPA sudo add-apt-repository ppa:ubuntu-wine/ppa 2.更新列表 sudo apt-get update 3.安装Wine sud ...
- Halcon的数据类型
两大类: 1.图形参数Iconic (image, region, XLD) 2.与控制参数Control (string, integer, real, handle), 在Halcon算子的参数中 ...
- git配置用户名邮箱,全局配置/单仓库配置
在项目根目录下进行单仓库配置(作用域只在本仓库下): git config user.name "gitlab's Name" git config user.email &quo ...