• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ASP.NET Core 如何使用Mvc相关技术建立Controller、Tag Helper (上)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

使用Mvc相关技术来完善一下前几篇文章的小栗子。。。

  • Controller
  • Tag Helper
  • Settings
  • View Component
  • Razor Page

首先添加一个Model文件夹

Department部门类(1):

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Department
    {
        public int Id { get; set; }
        [Display(Name ="部门名称")]
        public string Name { get; set; }
        public string Location { get; set; }
        public int EmployeeCount { get; set; }
    }
}

 Employee员工类(多):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public int DepartmentId { get; set; } //外键
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Gender Gender { get; set; }
        public bool Fired { get; set; }
    }

    public enum Gender
    { 
        女=0,
        男=1
    }
}

CompanySummary类:统计员工总数以及每个部门平均员工数量

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
    /// <summary>
    /// 公司
    /// </summary>
    public class CompanySummary
    {
        //员工总数
        public int EmployeeCount { get; set; }
        //部门平均员工数量
        public int AverageDepartmentEmployeeCount { get; set; }
    }
}

添加一个Services文件夹,在文件夹里面添加两个服务。

一个是IDepartmentService接口,一个是IEmployeeService接口

IDepartmentService:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public interface IDepartmentService
    {
        //获取所有部门
        Task<IEnumerable<Department>> GetAll();
        //通过Id获取部门
        Task<Department> GetById(int id);
        Task<CompanySummary> GetCompanySummary();
        //添加部门
        Task Add(Department department);
    }
}

接下来就是实现这两个接口!同样是在Services文件夹里面添加对应的实现接口的两个类

DepartmentService类:

首先将定义的departmentService类继承接口IDepartmentService 实现接口方法 。

通过readonly定义一个只读的List集合,在构造数里面添加几条部门数据。

GetAll()方法:返回类型为Task。这里涉及到了C#的异步编程。

GetById():根据部门Id进行查询。

GetCompanySummary():查询部门总人数以及每个部门的平均人数

Add():新增,将新增的Id在部门最大Id+1即可。

写到这里呢,就是一套服务了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public class DepartmentService:IDepartmentService
    {
        private readonly List<Department> _departments = new List<Department>();
        public DepartmentService()
        {
            _departments.Add(new Department
            {
                Id=1,
                Name="HR",
                EmployeeCount=16,
                Location="北京"
            });
            _departments.Add(new Department
            {
                Id = 2,
                Name = "HR1",
                EmployeeCount = 52,
                Location = "上海"
            });
            _departments.Add(new Department
            {
                Id = 3,
                Name = "HR2",
                EmployeeCount = 200,
                Location = "广州"
            });
        }

        public Task<IEnumerable<Department>> GetAll()
        {
            return Task.Run(()=>_departments.AsEnumerable());
        }
        public Task<Department> GetById(int id)
        {
            return Task.Run(() => _departments.FirstOrDefault(x => x.Id == id));
        }

        public Task<CompanySummary> GetCompanySummary()
        {
            return Task.Run(() =>
            {
                return new CompanySummary
                {
                    EmployeeCount = _departments.Sum(x => x.EmployeeCount),
                    AverageDepartmentEmployeeCount = (int)_departments.Average(x => x.EmployeeCount)
                };
            });
        }
        public Task Add(Department department)
        {
            //现有部门最大Id+1就是最新Id
            department.Id = _departments.Max(x => x.Id) + 1;
            _departments.Add(department);
            return Task.CompletedTask;
        }
    }
}

IEmployeeService:接下来也是一套服务。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public interface IEmployeeService
    {
        Task Add(Employee employee);
        Task<IEnumerable<Employee>> GetByDepartmentId(int departmentId);
        Task<Employee> Fire(int id);
    }
}

EmployeeService类:这个类里面的方法和部门类的方法基本上差不多,也都是返回Task。

GetByDepartmentId():根据部门Id查询该部门所有人员。

Add():一样也是做新增员工操作。

Fire():这个方法主要是负责员工是否已离职,离职:False、在职:True(默认)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Models;

namespace WebApplication1.Services
{
    public class EmployeeService : IEmployeeService
    {
        private readonly List<Employee> _employees = new List<Employee>();

        public EmployeeService()
        {
            _employees.Add(new Employee
            {
                Id=1,
                DepartmentId=1,
                FirstName="Nick",
                LastName="Carter",
                Gender=Gender.男
            });
            _employees.Add(new Employee
            {
                Id = 2,
                DepartmentId = 1,
                FirstName = "Michael",
                LastName = "Jackson",
                Gender = Gender.男
            });
            _employees.Add(new Employee
            {
                Id = 3,
                DepartmentId = 1,
                FirstName = "Mariah",
                LastName = "Carey",
                Gender = Gender.女
            });
            _employees.Add(new Employee
            {
                Id = 4,
                DepartmentId = 2,
                FirstName = "Avril",
                LastName = "CarLavigneter",
                Gender = Gender.女
            });
            _employees.Add(new Employee
            {
                Id = 5,
                DepartmentId = 3,
                FirstName = "小希",
                LastName = "",
                Gender = Gender.女
            });
            _employees.Add(new Employee
            {
                Id = 6,
                DepartmentId = 3,
                FirstName = "小伟",
                LastName = "",
                Gender = Gender.男
            });
        }

        public Task Add(Employee employee)
        {
            employee.Id = _employees.Max(x => x.Id) + 1;
            _employees.Add(employee);
            return Task.CompletedTask;
        }

        public Task<Employee> Fire(int id)
        {
            return Task.Run(() =>
            {
                var employee = _employees.FirstOrDefault(e => e.Id == id);
                if (employee != null)
                {
                    employee.Fired = true;
                    return employee;
                }
                return null;
            });
        }

        public Task<IEnumerable<Employee>> GetByDepartmentId(int departmentId)
        {
            return Task.Run(() => _employees.Where(x=>x.DepartmentId==departmentId));
        }
    }
}

这两套服务搞定后,就是注册这两套服务了。。。

去到Startup类:

public void ConfigureServices(IServiceCollection services)
{
     //负责配置依赖注入
     //DI 依赖注入机制依赖于IOC容器(控制反转)
     //使用Asp.NET Core MVC,所有需要通道控制器和视图要进行注册一下m\v\c(通过services服务注册)
     services.AddControllersWithViews();

     //分别注册服务
     services.AddSingleton<IDepartmentService, DepartmentService>();
     services.AddSingleton<IEmployeeService, EmployeeService>();
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.NET MVC2 辅助方法发布时间:2022-07-10
下一篇:
ASP.NET性能优化之分布式Session发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap