MVC 6 一些不晓得的写法

今天在看 Scott Guthrie 的一篇博文《Introducing ASP.NET 5》,在 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" })
<div class="form-group">
@Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.UserName, "", new { @class = "text-danger" })
</div>
</div>

另类写法:

<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="UserName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>

上面一般是我们在 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>();
}

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

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

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

@using WebApplication23
@inject TimeService TimeSvc <h3>@ViewBag.Message</h3> <h3>
@TimeSvc.Ticks From Razor
</h3>

上面为获取注入的对象,关键字为 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";
} <div class="jumbotron">
<h1>ASP.NET vNext</h1>
</div> <div class="row">
<div class="col-md-4">
@Component.Invoke("PriorityList", 1)
</div>
</div>

上面是 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<IViewComponentResult> 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<TodoList.Models.TodoItem>

<h2> PVC Named Priority Component View</h2>
<h4>@ViewBag.PriorityMessage</h4>
<ul>
@foreach (var todo in Model)
{
<li>@todo.Title</li>
}
</ul>
@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<int> GetCount()
{
return await Task.FromResult(db.TodoItems.Count());
} public async Task<int> 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<TodoList.Services.StatisticsService>();
}

调用代码:

@inject TodoList.Services.StatisticsService Statistics
@{
ViewBag.Title = "Home Page";
} <div class="jumbotron">
<h1>ASP.NET vNext</h1>
</div> <div class="row">
<div class="col-md-4">
@await Component.InvokeAsync("PriorityList", 4, true) <h3>Stats</h3>
<ul>
<li>Items: @await Statistics.GetCount()</li>
<li>Completed:@await Statistics.GetCompletedCount()</li>
<li>Average Priority:@await Statistics.GetAveragePriority()</li>
</ul>
</div>
</div>

参考资料:

MVC 6 写法的更多相关文章

  1. JS 实现MVC的写法

    案例:当select 下拉选择框值变化时,显示其值(不是文本) 常规写法 <h3>JavaScript no MVC</h3>  <div>   <selec ...

  2. MVC系列——MVC源码学习:打造自己的MVC框架(四:了解神奇的视图引擎)

    前言:通过之前的三篇介绍,我们基本上完成了从请求发出到路由匹配.再到控制器的激活,再到Action的执行这些个过程.今天还是趁热打铁,将我们的View也来完善下,也让整个系列相对完整,博主不希望烂尾. ...

  3. 【开源】 bsf.mvc spingboot的扩展

    springboot的扩展实现,让springboot开发更加简单:形成demo模板,以后开发更方便. 开源地址:https://gitee.com/chejiangyi/bsf.mvc/tree/m ...

  4. mvc中的表现和数据分离怎么理解?

    使用过 JavaScript框架(如 AngularJS, Backbone)的人都很熟悉在UI(用户界面,前端)中mvc的工作机理.这些框架实现了MVC,使得在一个单页面中实现根据需要变化视图时更加 ...

  5. ASP.NET MVC升级到ASP.NET Core MVC踩坑小结

    写在前面 ASP.NET Core是微软新推出的支持跨平台.高性能.开源的开发框架,它的优势不必多说,因为已经说得太多了.当然,现在依然有着数量庞大的系统运行于.NET Framework上,由于有大 ...

  6. Android mvp模式、mvvm模式

    MVC和MVP的区别2007年08月08日 星期三 上午 09:23 MVC和MVP到底有什么区别呢? 从这幅图可以看到,我们可以看到在MVC里,View是可以直接访问Model的!从而,View里会 ...

  7. Go语言Web框架gwk介绍 1

    Go语言Web框架gwk介绍 (一)   今天看到Golang排名到前30名了,看来关注的人越来越多了,接下来几天详细介绍Golang一个web开发框架GWK. 现在博客园支持markdown格式发布 ...

  8. ASP.NET Web API 之一 入门篇

    一.基于RESTful标准的Web Api 原文讲解:https://www.cnblogs.com/lori/p/3555737.html 微软的web api是在vs2012上的mvc4项目绑定发 ...

  9. Springboot学习问题记录

    1.spring boot与cloud构建微服务,返回数据从json变成了xml 问题:本身spingboot项目是用@RestController注解,返回结果也是json格式,但是结合spring ...

随机推荐

  1. Socket方法LAN多线程文件传输

    1.思维:为了实现各种文件的大小可以被发送和接收的,它可以被设置为发送和接收缓冲器环.并记录文件的位置读取,假设读入缓冲区的字节的特定数目大于缓冲区的大小较小.然后该文件被发送,退出发送周期,关闭连接 ...

  2. HDU 4917 Permutation

    意甲冠军: 序列p1.p2.p3--pn由1.2.3--n这些数字  现在给出一些条件pi<pj  部条件的排列的个数 思路: 非常easy想到用一条有向的线连接全部的pi和pj  那么就构成了 ...

  3. 定向爬虫之爬一爬各个学校新闻的认识(【1】对Url的认识)

    昨天早上,我习惯性的打开博客园,看一看别人的写的博客.突然想起,自己好像没有写过什么博客,所以就心血来潮,把我现在做得事情写出来, 这也是对我目前的学习的一种总结.望大神指点.... 对于一间学校的新 ...

  4. tomcatserver乱码问题,tomcat与数据库之间的编码统一转换

    在tomcat文件夹的conf文件夹下,改动server.xml文件,在以下截图中的位置加上URIEncoding="UTF-8"则表示tomcat编码转换为utf-8风格, 一般 ...

  5. Task的异步模式

    Task的异步模式 返回该系列目录<基于Task的异步模式--全面介绍> 生成方法 编译器生成 在.NET Framework 4.5中,C#编译器实现了TAP.任何标有async关键字的 ...

  6. Android: ADT 23.0.2

    http://pan.baidu.com/s/1gdnBUUJ 版权声明:本文博主原创文章.博客,未经同意不得转载.

  7. Bob大叔观OO原则

    Bob大叔观OO原则 上篇总结了经典的23种 设计模式,详细的解读后期会陆续的详细揭开.使用设计模式的根本原因就是为了增强代码的复用性和可维护性.而面向对象是实现代码复用的有效途径,所以这里有必要了解 ...

  8. C++教程之lambda表达式一

    什么是Lambda? C++ 11增加了一个很重要的特性--Lambda表达式.营里(戴维营)的兄弟都对Objective-C很熟悉,很多人多block情有独钟,将各种回调函数.代理通通都用它来实现. ...

  9. mybatis generator插件开发

    mybatis现在普遍使用的每一个人DAO框架.mybatis generator它可以基于数据库中的表结构,生成自己主动mybatis代码和配置文件,方便使用,当然,实际的使用过程中.generat ...

  10. 关于Java和.NET之间的通信问题(JSON)

    前言: 最近项目在某XX领导的所谓指引下,非要转型Java,转就转吧,在转的过程前期是个痛苦期,特别.NET旧有项目和Java新项目需要通信时. 进入主题,Java和.NET之间需要通信,这时媒介很多 ...