上一篇搭建了页面,这里写下功能。

这里我用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的更多相关文章

  1. 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 ...

  2. SlickOne -- 基于Dapper, Mvc和WebAPI 的快速开发框架

    前言:在两年前,项目组推出了基于Dapper,Mvc和WebApi的快速开发框架,随着后续Slickflow产品的实践和应用,今再次对SlickOne项目做以回顾和总结.其目的是精简,持续改进,保持重 ...

  3. SQLSERVER 数据库性能的的基本 MVC + EF + Bootstrap 2 权限管理

    SQLSERVER 数据库性能的基本 很久没有写文章了,在系统正式上线之前,DBA一般都要测试一下服务器的性能 比如你有很多的服务器,有些做web服务器,有些做缓存服务器,有些做文件服务器,有些做数据 ...

  4. [转帖]Asp.Net MVC EF各版本区别

    Asp.Net MVC EF各版本区别 https://www.cnblogs.com/liangxiaofeng/p/5840754.html 2009年發行ASP.NET MVC 1.0版 201 ...

  5. SlickOne敏捷开发框架介绍(一) -- 基于Dapper, Mvc和WebAPI 的快速开发框架

    前言:在两年前(最初发布时间:2013年1月9日(csdn),当前文章时间2015年11月10日),项目组推出了基于Dapper,Mvc和WebApi的快速开发框架,随着后续Slickflow产品的实 ...

  6. [转]Asp.Net MVC EF各版本区别

    本文转自:http://www.cnblogs.com/liangxiaofeng/p/5840754.html 2009年發行ASP.NET MVC 1.0版 2010年發行ASP.NET MVC ...

  7. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(24)-权限组的设计和实现(附源码)(终结)

    ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   (1):框架搭建    (2):数据库访问层的设计Demo    (3):面向接口编程   (4 ):业务逻辑层的封装    ...

  8. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(23)-设置角色遗留问题和为权限设置角色以及EasyUI Tabs的使用

    ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   (1):框架搭建    (2):数据库访问层的设计Demo    (3):面向接口编程   (4 ):业务逻辑层的封装    ...

  9. ASP.NET MVC+EF框架+EasyUI实现权限管理系列(22)-为用户设置角色

    ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇)   (1):框架搭建    (2):数据库访问层的设计Demo    (3):面向接口编程   (4 ):业务逻辑层的封装    ...

随机推荐

  1. Java在Service层异常封装

    dao层不需要抛出异常,应该在service层抛出异常,可以是自定义的异常,也可以包装异常,然后在controller中定义exception handler统一处理或者单独处理. 参考: https ...

  2. Linux 安装 yum

    1.使用RedHat系统不能正常使用yum安装 由于RedHat没有注册,所有不能使用它自身的资源更新, 查看安装源是否安装: # rpm –qa|grep yum 卸载安装源: # rpm –e – ...

  3. IOPS计算

    Device Type IOPS 7,200 rpm SATA drives HDD ~75-100 IOPS[2] 10,000 rpm SATA drives HDD ~125-150 IOPS[ ...

  4. 基于Python项目的Redis缓存消耗内存数据简单分析(附详细操作步骤)

    目录 1 准备工作 2 具体实施   1 准备工作 什么是Redis? Redis:一个高性能的key-value数据库.支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使 ...

  5. eclipse default handler IHandler interface “the chosen operation is not enabled”

    NOTE: These two methods: Tip: Subclass AbstractHandler rather than implementing IHandler. but you ca ...

  6. docker部署maven私有仓库 nexus3

    docker pull sonatype/nexus3: docker run -d --name nexus3.x --network host -v /volume-data/nexus3/nex ...

  7. 【MySQL】MySQL视图创建、查询。

    视图是指计算机数据库中的视图,是一个虚拟表.关系型数据库中的数据是由一张一张的二维关系表所组成,简单的单表查询只需要遍历一个表,而复杂的多表查询需要将多个表连接起来进行查询任务.对于复杂的查询事件,每 ...

  8. CART决策树(分类回归树)分析及应用建模

    一.CART决策树模型概述(Classification And Regression Trees)   决策树是使用类似于一棵树的结构来表示类的划分,树的构建可以看成是变量(属性)选择的过程,内部节 ...

  9. 从HTML Components的衰落看Web Components的危机 HTML Components的一些特性 JavaScript什么叫端到端组件 自己对Polymer的意见

    http://blog.jobbole.com/77837/ 原文出处: 徐飞(@民工精髓V) 搞前端时间比较长的同学都会知道一个东西,那就是HTC(HTML Components),这个东西名字很现 ...

  10. Disruptor学习笔记

    前言 以前一直听说有Disruptor这个东西,都说性能很强大,所以这几天自己也看了一下. 下面是自己的学习笔记,另外推荐几篇自己看到写的比较好的博客: Disruptor——一种可替代有界队列完成并 ...