MVC代码优先构造简单小系统

MVC + jQuery ajax + Bootstrap + LayUI 构造简单小系统


1. 生成数据库和表(Models文件夹)
  • 构造Context 上下文 (TicketContext类)

    public class TicketContext:DbContext
    {
         public TicketContext() : base("con")
         {
            Database.SetInitializer<TicketContext>(null);
         }
    
         protected override void OnModelCreating(DbModelBuilder modelBuilder)
         {
        	base.OnModelCreating(modelBuilder);
         	modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        	modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    	}
    }
    
  • 添加ConnectionStrings (WebConfig中)

    <connectionStrings>
    	<add name="con" connectionString="server=.;database=PerformanceTicket;Trusted_Connection=SSPI" providerName="System.Data.SqlClient" />
    </connectionStrings>
    
  • 构造BaseEntity类 (有所有类共有的属性的基类)

    public class BaseEntity
    {
    	public int Id { get; set; }
    	public DateTime CreateTime { get; set; } = DateTime.Now;
    	public bool IsRemoved { get; set; }
    }
    
  • 构造所有对象的类

    • 继承BaseEntity
    • 自己的属性
    • 外键属性 (联系为1:n、m:n)
    public class Number:BaseEntity
    {
         public DateTime NumberTime { get; set; }
         public double Account { get; set; } = 1;
    
         public int Zaoniao { get; set; } = 9999;
         public int Xianchang { get; set; } = 9999;
         public int Yushou { get; set; } = 9999;
    
    
         [ForeignKey(nameof(Performance))]
         public int PerformanceId { get; set; }
         public Performance Performance { get; set; }
    }
    ...
    
  • 将所有类加到TicketContect中 (以属性的形式,TicketContext类中)

    public DbSet<Number> Numbers { get; set; }
    ...
    
  • 初始化数据库

    • 申请开始迁移

      Enable-Migrations
      
    • 生成创建和删除表的代码

      Add-Migrations name
      
    • 生成数据库和表

      Update-Database
      
2. 在DAL层生成基本存储过程(DAL文件夹)
  • 构造模板Service类 (BaseService)

    public class BaseService<T>: IDisposable where T: BaseEntity, new()
    {
    	private readonly TicketContext _db;
    	public BaseService(TicketContext db)
    	{
    		_db = db;
    	}
    	public void Dispose()
        {
            _db.Dispose();
        }
    }
    
    • IDisposable释放对象
    • 构造函数接受数据库连接
  • 在模板类中添加增删改查操作

    • 添加数据

      public void Create(T model)
      {
      	_db.Set<T>().Add(model);
      	_db.SaveChanges();
      }
      
    • 删除数据

      public void Remove(int id)
      {
       	// 打开修改权限(打开保存后验证=false)
      	_db.Configuration.ValidateOnSaveEnabled = false;
      	var t = new T{Id = id};
      	_db.Entry(t).State = EntityState.Unchanged;
      	t.IsRemoved = true;
      	_db.SaveChanges();
      	_db.Configuration.ValidateOnSaveEnabled = true;
      }
      
    • 查找某个数据、查找所有数据

      public T GetOneById(int id)
      {
      	return GetAll().First(m => m.Id == id);
      }
      
      public IQueryable<T> GetAll()
      {
      	return _db.Set<T>().Where(m => !m.IsRemoved).AsNoTracking();
      }
      
    • 修改数据

      public void Edit(T model)
      {
      	_db.Configuration.ValidateOnSaveEnabled = false;
      	_db.Entry(model).State = EntityState.Modified;
      	_db.SaveChanges();
      	_db.Configuration.ValidateOnSaveEnabled = true;
      }
      
  • 构造所有对象的Service类

    public class SessionService:BaseService<Session>
    {
    	public SessionService() : base(new TicketContext())
    	{
    	}
    }
    ...
    
3. 在BLL层生成逻辑处理(BLL文件夹)
  • 构造Manager类 (根据主要操作的对象分类)

    public class UserManager
    {
    	public bool Login(string uid, string pwd, out int id)
    	{
    		using (var userSvc = new UserService())
    		{
    			if (userSvc.GetAll().Any(m => m.Uid == uid && m.Pwd == pwd))
             {
             	id = userSvc.GetAll().First(m => m.Uid == uid).Id;
             	return true;
             }
             id = 0;
             return false;
         }
     }
    
     public bool Register(string uid, string pwd, out User user)
     {
         using (var userSvc = new UserService())
         {
         	if (userSvc.GetAll().Any(m => m.Uid == uid))
         	{
             	user = new User();
             	return false;
             }
             user = new User()
             {
             	Uid = uid,
             	Pwd = pwd
             };
    
    			userSvc.Create(user);
    
             return true;
         }
    	}
    }
    ...
    
4. 在Controller中生成视图和API
  • 构造视图

    • 右键View生成视图
    public class UserController : Controller
    {
         [HttpGet]
         public ActionResult Login()
         {
             return View();
         }
    
         [HttpGet]
         public ActionResult Register()
         {
             return View();
         }
    }
    
  • 构造API

    • API也放在UserController中
    #region Login
     [HttpPost]
     public ActionResult Login(string uid, string pwd)
     {
         var result = new UserManager().Login(uid, pwd, out var id);
         var isAdmin = false;
    
         if (result)
         {
             Session["id"] = id;
             isAdmin = new UserManager().IsAdmin(id);
         }
    
         return Json(new ResponseModel()
         {
             Code = (result ? 1 : 0),
             Msg = isAdmin.ToString()
         });
     }
    
    #endregion
    
5. 导入需要的包
  • Bootstrap 快速使用的前端框架

    • 从Content文件夹中找到css文件(或 .min.css)直接拖入到标签内
    • 从Scripts文件夹中找到js文件直接拖入到标签内
    • 文档入口:https://code.z01.com/v4/docs/
  • jQuery ajax 前后端数据交换(客户端和服务端)

    • 从Scripts文件夹中直接拖入到标签内
  • Layer 弹层组件

    • 从Content文件夹中找到css文件(或 .min.css)直接拖入到标签内
    • 从Scripts文件夹中找到js文件直接拖入到标签内
    • 文档入口:https://www.layui.com/doc/modules/layer.html
6.常遇见的经典问题
  • 母版_Layout

    ​ 当要写的几个页面都需要用到一些组件时,我们可以把他们放到母版“_Layout.cshtml”内,需要加入下面几行代码:

    // 放入到需要补充代码的地方,子页面的代码会嵌入到这里
    @RenderBody()
    
    // 放入<head></head>内
    @RenderSection("css", false)
    // 子页面的css可以放在这里,通过@section css调用,加入新的css自定义样式
    @section css{
         <style>
                ...
         </style>
    }
    
    // 放入<body></body>内
    @RenderSection("script", required: false)
    // 子页面的script可以放在这里,通过@section script调用,加入新的函数
    @section css{
         <style>
         		...
         </style>
    }
    
  • ViewBag

    ​ 将数据从控制器传给视图,或者将数据从视图传给视图:

    @{
     	ViewBag.Title = $"AllPerformances";
     	List<Performance> performances = 	ViewBag.Performances;
    }
    
  • 初始化页面

    ​ 在页面刷新时,就需要展示一些可变化的数据,需要使用jQuery ajax进行数据交换,函数写法如下:

    $(function() {
     	...
    });
    
  • 组件的显示与隐藏

    document.getElementById("search").style.display = "none";
    
  • 判断当前是否有用户登录

    <input value="@((ViewBag.UserId != null && ViewBag.UserId != 0)? 1: 0)" type="hidden" id="confirmLogin"/>
     
    function confirmLogin() {
     	return $('#confirmLogin').val() == 1;
    }
    
  • 常用layui弹出层

    layer.msg('请确认演出名称!', { time: 2000 });
    
    layer.confirm(`确定吗?`,
                  {
        btn: ['确定', '取消']function(){},
        function(){}
    })
    
    layer.closeAll();
    
  • 多选框选中改变时,改变另一个组件

    $(document).ready(function() {
         $("#selectNumber").change(function() {
                ...
         });
    });
    
  • 多选框的选中值

    let value = $("#selectValue").children('option:selected').val();
    
  • 记录所有name属性相同的组件的value

    let numbers = [];
    $('input[name^=number]').each(function(aIdx, aElmt) {
    	numbers.push(aElmt.value);
    });
    
  • 组件加减框

    <div id="box">
     <div id="aaa">
    	 	<label for="number">只有一个label,有没有都可以</label>
     </div>
    </div>
    
    $(function() {
    	addCom();
    	$("#box").on('click','.addp',function() {
    		addCom();
    	});
    	$("#box").on("click",'.delp',function() {
    		$(this).parent().remove();
    	});
    });
    
    function addCom(a="", b="", c="", d="") {
        let aaa = $('#aaa');
        aaa.append(
            `要添加的组件代码`
        );
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值