上一篇搭建了页面,这里写下功能。
这里我用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 = 0; 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 - 1)).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="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 = "300px" }) </td> </tr> <tr> <td>介绍:</td> <td> @Html.TextBoxFor(s => s.Introduce, new { @class = "easyui-textbox", style = "100%", @data_options = "multiline:true,height:80" }) </td> </tr> <tr> <td>排序值:</td> <td> @Html.TextBoxFor(s => s.OrderId, new { @class = "easyui-numberspinner", style = "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、点击确定之后表单中的数据就添加进数据库了。