ASP.NET MVC 6 一些不晓得的写法
今天在看 Scott Guthrie 的一篇博文《Introducing ASP.NET 5》,在 MVC 6 中,发现有些之前不晓得的写法,这边简单记录下,算是对自己知识的补充,有些我并没有进行尝试,因为我使用的 Visual Studio 2015 CTP 5,但是有些并没有支持(下面第一点),现在 Visual Studio 2015 已经更新到 CTP 6 了,本来还想尝试下,看了下 4.6G 的大小,想想还是算了。
- Visual Studio 2015 CTP 6(说明及下载)
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>
参考资料:
ASP.NET MVC 6 一些不晓得的写法的更多相关文章
- ASP.NET MVC 4 异步加载控制器
ASP.NET 4 Developer preview中的异步操纵器 在放弃了对.NET 3的支持之后, ASP.NET MVC 4 彻底拥抱了Task类库, 你不需求再蛋疼的给每个Action写两个 ...
- Asp.Net MVC 扩展 Html.ImageFor 方法详解
背景: 在Asp.net MVC中定义模型的时候,DataType有DataType.ImageUrl这个类型,但htmlhelper却无法输出一个img,当用脚手架自动生成一些form或表格的时候, ...
- ASP.NET MVC - 安全、身份认证、角色授权和ASP.NET Identity
ASP.NET MVC - 安全.身份认证.角色授权和ASP.NET Identity ASP.NET MVC内置的认证特性 AuthorizeAttribute特性(System.Web.Mvc)( ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- 使用Visual Studio 2015 开发ASP.NET MVC 5 项目部署到Mono/Jexus
最新的Mono 4.4已经支持运行asp.net mvc5项目,有的同学听了这句话就兴高采烈的拿起Visual Studio 2015创建了一个mvc 5的项目,然后部署到Mono上,浏览下发现一堆错 ...
- 一百元的智能家居——Asp.Net Mvc Api+讯飞语音+Android+Arduino
大半夜的,先说些废话提提神 如今智能家居已经不再停留在概念阶段,高大上的科技公司都已经推出了自己的部分或全套的智能家居解决方案,不过就目前的现状而言,大多还停留在展厅阶段,还没有广泛的推广起来,有人说 ...
- Asp.net MVC 传递数据 从前台到后台,包括单个对象,多个对象,集合
今天为大家分享下 Asp.net MVC 将数据从前台传递到后台的几种方式. 环境:VS2013,MVC5.0框架 1.基本数据类型 我们常见有传递 int, string, bool, double ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点
在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航
ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...
随机推荐
- zookeeper工作原理、安装配置、工具命令简介
1.Zookeeper简介 Zookeeper 是分布式服务框架,主要是用来解决分布式应用中经常遇到的一些数据管理问题,如:统一命名服务.状态同步服务.集群管理.分布式应用配置项的管理等等. 2.zo ...
- List、Map、Set三个接口,存取元素时,各有什么特点?
List 以特定次序来持有元素,可有重复元素:Set 无法拥有重复元素,内部排序(无序):Map 保存key-value值,value可多值.
- html中的图像动态加载问题
首先要说明下文档加载完成是什么概念 一个页面http请求访问时,浏览器会将它的html文件内容请求到本地解析,从窗口打开时开始解析这个document,页面初始的html结构和里面的文字等内容加载完成 ...
- 05.DOM
DOM基础 什么是DOM 标签元素节点浏览器支持情况 火狐支持最好 谷歌其次 ie最差 尤其是ie6-8DOM节点节点分为:元素节点和文本节点 测试节点的类型用nodeTypenodeType 为3 ...
- 关于PHP中<?php ?>的结束标签是否添加
在纯PHP代码中“?>”结束标签最好不要添加 原因:容易导致输出多余的空白或者换行,以及由此产生的一些报错. 比如a.php文件中,在?>标签后面多出空格或者换行,而当b.php文件引入a ...
- angularjs服务-service
Service 的特性 ①service都是单例的 ②service由$injector 负责实例化 ③service在整个应用的声明周期中存在,可以用来共享数据 ④在需要使用的地方利用依赖注入ser ...
- CGI和ISAPI
1) CGI概念CGI即通用网关接口(Common Gateway Interface),它是一段程序,运行在服务器上,提供同客户端HTML页面的交互,通俗的讲CGI就象是一座桥,把网页和WEB服务器 ...
- 使用java反射机制编写Student类并保存
定义Student类 package org; public class Student { private String _name = null; ; ; public Student() { } ...
- 字符串混淆技术应用 设计一个字符串混淆程序 可混淆.NET程序集中的字符串
关于字符串的研究,目前已经有两篇. 原理篇:字符串混淆技术在.NET程序保护中的应用及如何解密被混淆的字符串 实践篇:字符串反混淆实战 Dotfuscator 4.9 字符串加密技术应对策略 今天来 ...
- ASP.NET跨平台实践:无需安装Mono的Jexus“独立版”
在Linux上运行ASP.NET网站或WebApi的传统步骤是,先安装libgdiplus,再安装mono,然后安装Jexus.在这个过程中,虽然安装Jexus是挺简便的一件事,但是安装mono就相对 ...