view components介绍
view components介绍
在ASP.NET MVC 6中,view components (VCs) 功能类似于虚拟视图,但是功能更加强大。 VCs兼顾了视图和控制器的优点,你可以把VCs 看作一个Mini 控制器。它负责控制应用中的某一功能模块,例如:
- 动态导航菜单
- 标签云
- 登录面板
- 购物车
- 最近文章
- 博客侧边栏
假如使用VC 创建了登录面板,可以在很多场景中调用,例如:
- 用户没有登录
- 用户已登录,需要退出使用其他帐号登录或者管理其他帐号。
- 如果当前登录角色为管理员,渲染管理员登录面板
你可以根据用户的需求获取数据进行渲染。添加VC到需要该视图控件的页面。
VC 包含两部分,类 (一般继承于ViewComponent) 和调用VC类中方法的Razor 视图。类似于ASP.NET 控制器, VC 可以作为POCO使用,但是更多用户倾向于使用从 VewComponent中继承而来的方法和属性。
VC的创建方式有:
- 继承ViewComponent.
- 拥有 [ViewComponent] 属性,或者从拥有 [ViewComponent]属性派生的类。
- 创建名称已ViewComponent为后缀的类。
和controllers相同,VCs 必须是公开、非嵌套和非抽象的类。
添加view component 类
1. 创建名为ViewComponents的文件夹,View component 类可以包含在工程中的任何文件夹下。
2. 在ViewComponents 文件夹下创建PriorityListViewComponent.cs 类。.
3. 使用以下代码替代PriorityListViewComponent.cs 文件原有代码:

using System.Linq;
using Microsoft.AspNet.Mvc;
using TodoList.Models; namespace TodoList.ViewComponents
{
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,运行时将通过字符串"PriorityList" 从View中引用该类。在后续章节将会进行详细阐述。
· [ViewComponent] 属性用于设置引用VC的别名,例如,创建名称为XYZ的类,我们可以通过以下代码设置其引用别名:
[ViewComponent(Name = "PriorityList")]
public class XYZ : ViewComponent
· 组件使用构造注入器使数据内容生效,类似于 Todo 控制器的功能。
· 调用View中的公开方法,可以传递任意数量的参数。在异步版本中, InvokeAsync是可用的。在后续章节中我们将提及InvokeAsync 和多参数的使用方法。在之前的代码中,公开方法的返回值为代办事项(ToDoItems),优先级不低于maxPriority。
添加视图控件
1. 在Views\Todo 文件夹下创建Components文件夹,注意这个文件夹需要命名为Components。
2. 在Views\Todo\Components 文件夹下创建PriorityList 文件夹。文件夹名称必须和view component 类名称一致。或者类名去除后缀名称(如果在创建类时遵循惯例使用ViewComponent 作为后缀)。如果使用了ViewComponent属性。
3. 在Views\Todo\Components\PriorityList 文件夹下创建Default.cshtml Razor 视图,添加以下标记:

@model IEnumerable<TodoList.Models.TodoItem> <h3>Priority Items</h3>
<ul>
@foreach (var todo in Model)
{
<li>@todo.Title</li>
}
</ul>

Razor 视图包含并且显示了 TodoItems。如果 VC 调用方法没有传递视图的名称 (如例子中所示),那么默认情况下则调用视图名称对于方法。在后续的文章中,将阐述如何传递视图名称。
在views\todo\index.cshtml 视图底部添加包含有调用PriorityListViewComponent的div:

@model IEnumerable<TodoList.Models.TodoItem> <h3>Priority Items</h3>
<ul>
@foreach (var todo in Model)
{
<li>@todo.Title</li>
}
</ul>

标记 @await Component.InvokeAsync() 表示该语法用于调用VC。第一个参数是我们要调用的组件名称。其余参数参数传递给该VC。在这个例子中,我们传递“1”作为过滤的优先级。InvokeAsync 方法可以包含任意数量的参数。
以下图片显示了优先级列表:

@{
ViewBag.Title = "ToDo Page";
}
<div class="jumbotron">
<h1>ASP.NET vNext</h1>
</div>
<div class="row">
<div class="col-md-4">
@if (Model.Count == 0)
{
<h4>No Todo Items</h4>
}
else
{
<table>
<tr><th>TODO</th><th></th></tr>
@foreach (var todo in Model)
{
<tr>
<td>@todo.Title </td>
<td>
@Html.ActionLink("Details", "Details", "Todo", new { id = todo.Id }) |
@Html.ActionLink("Edit", "Edit", "Todo", new { id = todo.Id }) |
@Html.ActionLink("Delete", "Delete", "Todo", new { id = todo.Id })
</td>
</tr>
}
</table>
}
<div>@Html.ActionLink("Create New Todo", "Create", "Todo") </div>
</div>
<div class="col-md-4">
@Component.Invoke("PriorityList", 1)
</div>
</div>


注意: VC通常被添加到 Views\Shared 文件夹下,因为它并不仅仅是controller。
添加InvokeAsync 到优先级组件
通过以下代码更新PriorityListViewComponent类:

using System.Linq;
using Microsoft.AspNet.Mvc;
using TodoList.Models;
using System.Threading.Tasks; namespace TodoList.ViewComponents
{
public class PriorityListViewComponent : ViewComponent
{
private readonly ApplicationDbContext db; public PriorityListViewComponent(ApplicationDbContext context)
{
db = context;
} // Synchronous Invoke removed. 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);
} private Task<IQueryable<TodoItem>> GetItemsAsync(int maxPriority, bool isDone)
{
return Task.FromResult(GetItems(maxPriority, isDone)); }
private IQueryable<TodoItem> GetItems(int maxPriority, bool isDone)
{
var items = db.TodoItems.Where(x => x.IsDone == isDone &&
x.Priority <= maxPriority); string msg = "Priority <= " + maxPriority.ToString() +
" && isDone == " + isDone.ToString();
ViewBag.PriorityMessage = msg; return items;
} }
}

注意: 这里移除了用于同步的Invoke 方法,使用更加强大的asynchronous方法替代。
修改 VC 视图显示优先级信息:

@model IEnumerable<TodoList.Models.TodoItem> <h4>@ViewBag.PriorityMessage</h4>
<ul>
@foreach (var todo in Model)
{
<li>@todo.Title</li>
}
</ul>

最后,更新 views\todo\index.cshtml 视图文件:

@* Markup removed for brevity. *@
<div class="col-md-4">
@await Component.InvokeAsync("PriorityList", 2, true)
</div>
</div>

以下图片展示了PriorityListViewComponent类和Index视图的修改效果:

指定视图名称
一些复杂的VC在某些情况下也许需要去指定特定的视图,以下代码是通过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);
}

更改 Views\Todo\Components\PriorityList\Default.cshtml 为 Views\Todo\Components\PriorityList\PVC.cshtml 视图。更改PVC视图控件来验证它的使用:

@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>

最后,需要更新 Views\Todo\Index.cshtml 文件:
刷新页面查看更改效果。
在MVC6中,更改controller(或其他任何代码)时,不需要重新编译或重新运行应用,仅需要保存代码并且刷新页面即可。
以上即为今天希望和大家分享的view components知识,下一篇文章我们将介绍以下两部分内容:
- 向视图中添加服务方法。
- 发布应用到公有云方法。
敬请期待。
原文链接:http://www.asp.net/vnext/overview/aspnet-vnext/vc
view components介绍的更多相关文章
- ASP.NET 5系列教程 (三):view components介绍
在ASP.NET MVC 6中,view components (VCs) 功能类似于虚拟视图,但是功能更加强大. VCs兼顾了视图和控制器的优点,你可以把VCs 看作一个Mini 控制器.它负责控制 ...
- [译]View components and Inject in ASP.NET MVC 6
原文:http://www.asp.net/vnext/overview/aspnet-vnext/vc 介绍view components view components (VCs) 类似于part ...
- Android Animation学习(六) View Animation介绍
Android Animation学习(六) View Animation介绍 View Animation View animation系统可以用来执行View上的Tween animation和F ...
- View Components as Tag Helpers,离在线模板编辑又进一步
在asp.net core mvc中增加了ViewComponent(视图组件)的概念,视图组件有点类似部分视图,但是比部分视图功能更加强大,它更有点像一个控制器. 使用方法 1,定义类派生自View ...
- [转] asp.net core Introducing View Components
本文转自:http://www.c-sharpcorner.com/uploadfile/8c19e8/asp-net-5-getting-started-with-asp-net-mvc-6/ In ...
- View的介绍和运用 && FlexBox布局
开始我们今天的项目学习啦~~~~~~ 1> 第一步当然是创建项目啦: 进入终端: 创建ViewDemo项目 命令如下啦,你看懂了对吧...嘻嘻!!! 2>View的介绍和运用 项目安装创建 ...
- Android的View类介绍-android的学习之旅(十三)
view概述 android绝大部分UI组件都放在android.view和android.widght包中,android的虽有UI组件都继承了View类. View类还有一个非常重要的子类:Vie ...
- mvc VIEW部分介绍
因为如果在view页面中的路径直接写死为<from action="/Home/Save" method="post">那么当Global.asax ...
- DAO层,Service层,Controller层、View层介绍
来自:http://jonsion.javaeye.com/blog/592335 DAO层 DAO 层主要是做数据持久层的工作,负责与数据库进行联络的一些任务都封装在此,DAO层的设计首先是设计DA ...
随机推荐
- UVA 847 - A Multiplication Game(游戏)
UVA 847 - A Multiplication Game 题目链接 题意:一个数一開始是1,每次轮流乘2-9,谁先大于n谁就赢,问谁胜 思路:博弈,找出必胜态.2-9为stan,10-18为ol ...
- [译]MVC应用程序生命周期
原文:MVC Application Lifecycle 来一探究竟在MVC应用程序中参与请求处理的各个不同组件. 目录: 序言 背景 UrlRoutingModule RouteHandler Mv ...
- POJ 3237 Tree (树链拆分)
主题链接~~> 做题情绪:了. 解题思路: 主要注意如何区间更新就ok了 . 树链剖分就是树上的线段树. 代码: #include<iostream> #include<sst ...
- POJ3617 Best Cow Line 馋
虽然这个问题很简单,但非常好,由于过程是很不错的.发展思路的比较 并鼓励人们,不像有些贪心太偏,推动穷人,但恼人 鉴于长N弦S,然后又空字符串STR.每当有两个选择 1:删S增加虚假的第一要素STR于 ...
- 实现BUG自动检测 - ASP.NET Core依赖注入
我个人比较懒,能自动做的事绝不手动做,最近在用ASP.NET Core写一个项目,过程中会积累一些方便的工具类或框架,分享出来欢迎大家点评. 如果以后有时间的话,我打算写一个系列的[实现BUG自动检测 ...
- iOS coreData
static int row=0; static const NSString *kStoryboardName = @"LRCoreDataViewController"; st ...
- struts1吊牌<logic:iterate>
<logic:iterate>主要用于处理网页上的输出集合,集合是其中一般下列之一: 1. java对象的数组 2. ArrayList.Vector.HashMap等 具体使用方法请參考 ...
- row_number()、rank()、dense_rank()、ntile()
原文:row_number().rank().dense_rank().ntile() SQL2005中row_number()等函数的用法 2005比2000新增了几个函数,分别是row_numbe ...
- [SignalR]初步认识以及安装
原文:[SignalR]初步认识以及安装 1.什么是ASP.NET SignalR? ASP .NET SignalR是一个 ASP .NET 下的类库,可以在ASP .NET 的Web项目中实现实时 ...
- height/innerHeight/outerHeight
<script> $(document).ready(function(){ alert("height:"+$("#div").height()) ...