WebApi+Bootstrap+KnockoutJs打造单页面程序(2)

/// <summary> /// Task WebAPI,提供数据服务 /// </summary> public class TasksController : ApiController { private readonly TaskRepository _taskRepository = TaskRepository.Current; public IEnumerable<Task> GetAll() { return _taskRepository.GetAll().OrderBy(a => a.Id); } public Task Get(int id) { var item = _taskRepository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return item; } [Route("api/tasks/GetByState")] public IEnumerable<Task> GetByState(string state) { IEnumerable<Task> results = new List<Task>(); switch (state.ToLower()) { case "": case "all": results = _taskRepository.GetAll(); break; case "active": results = _taskRepository.GetAll().Where(t => t.State == TaskState.Active); break; case "completed": results = _taskRepository.GetAll().Where(t => t.State == TaskState.Completed); break; } results = results.OrderBy(t => t.Id); return results; } [HttpPost] public Task Create(Task item) { return _taskRepository.Add(item); } [HttpPut] public void Put(Task item) { if (!_taskRepository.Update(item)) { throw new HttpResponseException(HttpStatusCode.NotFound); } } public void Delete(int id) { _taskRepository.Remove(id); } }

5. 使用Asp.net MVC Bundle对资源进行打包。对应的BundleConfig实现代码如下:

/// <summary> /// 只需要补充一些缺少的CSS和JS文件。因为创建模板的时候已经添加了一些CSS和JS文件 /// </summary> public class BundleConfig { // For more information on bundling, visit ?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/bootstrap-datepicker.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/bootstrap-datepicker3.min.css", "~/Content/site.css")); bundles.Add(new ScriptBundle("~/bundles/knockout").Include( "~/Scripts/knockout-{version}.js", "~/Scripts/knockout.validation.min.js", "~/Scripts/knockout.mapping-latest.js")); bundles.Add(new ScriptBundle("~/bundles/app").Include( "~/Scripts/app/app.js")); } }

6. 因为我们需要在页面上使得枚举类型显示为字符串。默认序列化时会将枚举转换成数值类型。所以要对WebApiConfig类做如下改动:

public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // 使得序列化使用驼峰式大小写风格序列化属性 config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 将枚举类型在序列化时序列化字符串 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter()); } }

注:如果上面没有使用驼峰小写风格序列化的话,在页面绑定数据的时候也要进行调整。如绑定的Name属性的时候直接使用Name大写,如果使用name方式会提示这个属性没有定义错误。由于JS是使用驼峰小写风格对变量命名的。所以建议大家加上使用驼峰小写风格进行序列化,此时绑定的时候只能使用"name"这样的形式进行绑定。这样也更符合JS代码的规范。 

7. 修改对应的Layout文件和Index文件内容。

Layout文件具体代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzpfzz.html