博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC 6 一些不晓得的写法
阅读量:7051 次
发布时间:2019-06-28

本文共 4681 字,大约阅读时间需要 15 分钟。

今天在看 Scott Guthrie 的一篇博文《》,在 MVC 6 中,发现有些之前不晓得的写法,这边简单记录下,算是对自己知识的补充,有些我并没有进行尝试,因为我使用的 Visual Studio 2015 CTP 5,但是有些并没有支持(下面第一点),现在 Visual Studio 2015 已经更新到 CTP 6 了,本来还想尝试下,看了下 4.6G 的大小,想想还是算了。

  • (说明及下载)

Scott Guthrie 博文中,大部分是对 ASP.NET 5 的综述,有些内容之前微软都已经发布过了,我只看了自己看兴趣的地方,当然评论内容也是不能漏掉的,除了这篇博文,我还搜刮了其他博文的一些内容,下面简单介绍下。

1. 统一开发模型

普通写法:

@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })

另类写法:

上面一般是我们在 View 写表单代码时候的写法,很明显,第二种比第一种更加简洁!

2. Dependency injection (DI) 写法

在 MVC 6 中是支持 DI 的,像 services.AddMvc(); 就是 MVC 6 使用自带的 IoC 进行注入,当然,除了注入这些 MVC 系统组件,我是没有在 ConfigureServices 中使用过自定义的对象注入,所以,我也是第一次晓得注入使用写法,示例:

public void ConfigureServices(IServiceCollection services){    services.AddMvc();    services.AddTransient
();}

TimeService 是一个自定义的类型,使用 AddTransient 方法,在 ConfigureServices 中进行注册。

public class HomeController : Controller{    [Activate]    public TimeService TimeService { get; set; }     // Code removed for brevity}

Activate 为注入对象属性,当然,你也可以使用构造函数进行注入,只不过是麻烦些。

@using WebApplication23@inject TimeService TimeSvc 

@ViewBag.Message

@TimeSvc.Ticks From Razor

上面为获取注入的对象,关键字为 inject。

3. View components 的一些内容

View components(VCs) ,我是第一次看到这个词,当然更没用过,component 是要素、组成、零件的意思,View components 可以理解为视图的补充,微软在介绍的时候,用到了一个词 mini-controller,可以看作是“微型控制器”,其实,像 @Html.LabelFor 这种写法也可以看作是 VC,说通俗一点,就是我们针对项目,写的一些帮助类。

创建 ViewComponent:

using System.Linq;using Microsoft.AspNet.Mvc;using TodoList.Models;namespace TodoList.ViewComponents{  //[ViewComponent(Name = "PriorityList")]  public class PriorityListViewComponent : ViewComponent  {    private readonly ApplicationDbContext db;    public PriorityListViewComponent(ApplicationDbContext context)    {      db = context;    }    public IViewComponentResult Invoke(int maxPriority)    {      var items = db.TodoItems.Where(x => x.IsDone == false &&                                        x.Priority <= maxPriority);      return View(items);    }  }}

创建的 PriorityListViewComponent 需要继承 ViewComponent,ViewComponent 是对 ViewComponent 名字的重写。

@{  ViewBag.Title = "ToDo Page";}

ASP.NET vNext

@Component.Invoke("PriorityList", 1)

上面是 ViewComponent 的调用代码,写法是 Component.Invoke,第一个参数是 ViewComponent 的类名,也可以是属性的重写名,第二个参数是优先级值,用于过滤我们要处理的项集合。

这是 ViewComponent Invoke 同步写法,也是最简单的一种,但是这种写法,现在已经在 MVC 6 中被移除了,说明:The synchronous Invoke method has been removed. A best practice is to use asynchronous methods when calling a database.

InvokeAsync 写法:

public async Task
InvokeAsync(int maxPriority, bool isDone){ string MyView = "Default"; // If asking for all completed tasks, render with the "PVC" view. if (maxPriority > 3 && isDone == true) { MyView = "PVC"; } var items = await GetItemsAsync(maxPriority, isDone); return View(MyView, items);}

调用代码:

@model IEnumerable

PVC Named Priority Component View

@ViewBag.PriorityMessage

    @foreach (var todo in Model) {
  • @todo.Title
  • }
@await Component.InvokeAsync("PriorityList", 4, true)

注意 ViewBag.PriorityMessage 的值,上面代码指定了视图名称。

4. 注入一个服务到视图

服务注入到视图,就是使用的上面第二点 DI 写法,示例服务:

using System.Linq;using System.Threading.Tasks;using TodoList.Models;namespace TodoList.Services{  public class StatisticsService  {    private readonly ApplicationDbContext db;    public StatisticsService(ApplicationDbContext context)    {      db = context;    }    public async Task
GetCount() { return await Task.FromResult(db.TodoItems.Count()); } public async Task
GetCompletedCount() { return await Task.FromResult( db.TodoItems.Count(x => x.IsDone == true)); } }}

ConfigureServices 中注册:

// This method gets called by the runtime.public void ConfigureServices(IServiceCollection services){  // Add MVC services to the services container.  services.AddMvc();  services.AddTransient
();}

调用代码:

@inject TodoList.Services.StatisticsService Statistics@{    ViewBag.Title = "Home Page";}

ASP.NET vNext

@await Component.InvokeAsync("PriorityList", 4, true)

Stats

  • Items: @await Statistics.GetCount()
  • Completed:@await Statistics.GetCompletedCount()
  • Average Priority:@await Statistics.GetAveragePriority()

参考资料:

转载地址:http://cydol.baihongyu.com/

你可能感兴趣的文章
UITableView:下拉刷新和上拉加载更多
查看>>
git 分支
查看>>
[ZJOI2017]树状数组
查看>>
内容显示在HTML页面底端的一些处理方式
查看>>
IE, FireFox, Opera 浏览器支持CSS实现Alpha半透明的方法
查看>>
bootstrap 智能表单 demo示例
查看>>
生成器函数进阶
查看>>
spring中InitializingBean接口使用理解(转)
查看>>
js作用域和作用域链
查看>>
NX签名//NXOpen VB.Net / C# Sign
查看>>
Mac下安装nginx
查看>>
Python菜鸟之路:Django 路由补充1:FBV和CBV - 补充2:url默认参数
查看>>
【转】生活感悟
查看>>
smarty练习: 设置试题及打印试卷
查看>>
maven 项目打包配置(build节点)
查看>>
保存指定品质的图片
查看>>
多目标跟踪baseline methods
查看>>
关于QT_Creator不能在线调试问题
查看>>
六、python小功能记录——递归删除bin和obj内文件
查看>>
阅读《移山之道》及讲义感想
查看>>