首页 > Web开发 > 详细

ASP.NET MVC

时间:2020-04-05 13:37:43      阅读:66      评论:0      收藏:0      [点我收藏+]

组成部分

Model, View, Controller

Razor 语法(.cshtml文件)

? ?

@{} 括号中 C# 代码

括号中写 C# 代码

@if()

{

? ?

}

@foreach()

{

? ?

}

? ?

@() 里面是 C# 表达式

? ?

~/ 开始为虚拟路径

Controller View 传递数据的方式

ViewData ViewBag 传递数据

  1. ViewData["name"] = value; 在 cshtml 中可直接使用 ViewData["name"] 获取
  2. ViewBag.name = value; 在 cshtml 中可使用 ViewBag.name 获取
  3. ViewData 和 ViewBag 共享数据

? ?

Model 传递数据

  1. Controller 的某个方法(Action)中返回 return View(model) 传入
  2. 弱类型
    1. 不在 cshtml 中没有声明 @model 模型类的全称
  3. 强类型
    1. 在 cshtml 中没有声明 @model 模型类的全称

? ?

请求中携带参数/path?id=1, Controller 中的 Action 如何接受

  1. MethodName(MethodNameModel model)
  2. MethodName(int id)

? ?

注意

  1. 默认一般情况下 Controller 中的 Action 是无法重载的, 否则会报错
  2. 但是通过添加 HttpGet, HttpPost 等 Attribute 则可以

Controller ActionResult

  1. ViewResult
  2. RedirectResult
  3. FileResult
  4. JsonResult
    1. return Json(data) // 默认不允许 GET

? ?

View() Redirect() 区别

  1. View() 是同一个请求(和其他的 Action 共享 ViewData 和 ViewBag)
  2. Redirect() 要求客户端发起一个新的请求(ViewData和ViewBag会清空)

Controller 属性

  1. ViewData
  2. ViewBag
  3. Session
  4. TempData: 取出就销毁

数据验证

? ?

在 model 的属性上添加属性

  1. Required
  2. StringLength(num, MinimumLength=num1)
  3. Range(a, b)
  4. Compare("")
  5. EmailAddress
  6. Phone
  7. RegularExpression

? ?

每个 Attribute 中有 ErrorMessage参数

? ?

自定义验证

  1. 继承 ValidationAttribute
    1. 重写 IsValid(object value)
  2. 如果希望实现正则表达式, 直接继承 RegularExpression
    1. 构造方法注意使用 base("期望的正则表达式")
    2. 在构造方法中 this.ErrorMessage = ""用来提示错误

Filters

? ?

全局的

  1. IAuthentication
  2. IAction

? ?

局部的

  1. 继承 FilterAttribute, 在期望的Action添加属性

? ?

FilterContext 对象

  1. filterContext.ActionDescriptor.ControllerDescriptor.ControllerName
  2. filterContext.ActionDescriptor.ActionName
  3. filterContext.HttpContext.Session
  4. filterContext.Result
  5. filterContext.HttpContext.Response(.Redirect()

? ?

注册

在 Global.asax.cs 中使用 GlobalFilters.Filters.Add(new Xxx())

Linq

示例代码

  1. from item in items

    select item.value

  2. from item in items

    select new {id=item.Id, Name=item.Name}

  3. from item in items

    orderby item.id descending

    select item

  4. from item in items

    join other in others on item.Id equals other.Id

    select new {itemName=item.name, otherName=other.Name}

? ?

MVC 项目三层架构

UI (MVC 就是 UI 层), BLL (业务逻辑层), DTO(Data Translate Object), DAL(数据访问层)

可以将 BLL 和 DAL 合并成 Service 层

ASP.NET MVC

原文:https://www.cnblogs.com/megachen/p/12636459.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!