在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 == )
{
<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", )
</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 > && 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", , 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 > && 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 文件:

刷新页面查看更改效果。

在进行开发时,使用 view components 可以更好的查看页面效果。如果再借助一些开发工具,还可以大大提高开发效率。ComponentOne Studio for ASP.NET 是ASP.NET平台上的一整套完备的开发工具包,包含的Web窗体控件、MVC scaffolding模板以及HTML5/JavaScript页面组件,仅通过几行代码就可以在系统中实现丰富的功能。

在MVC6中,更改controller(或其他任何代码)时,不需要重新编译或重新运行应用,仅需要保存代码并且刷新页面即可。

以上即为今天希望和大家分享的view components知识,下一篇文章我们将介绍以下两部分内容:

  • 向视图中添加服务方法。
  • 发布应用到公有云方法。

敬请期待。

原文链接:http://www.asp.net/vnext/overview/aspnet-vnext/vc

ASP.NET 5系列教程 (三):view components介绍的更多相关文章

  1. ASP.NET 5系列教程(七)完结篇-解读代码

    在本文中,我们将一起查看TodoController 类代码. [Route] 属性定义了Controller的URL 模板: [Route("api/[controller]") ...

  2. ASP.NET 5系列教程 (六): 在 MVC6 中创建 Web API

    ASP.NET 5.0 的主要目标之一是统一MVC 和 Web API 框架应用. 接下来几篇文章中您会了解以下内容: ASP.NET MVC 6 中创建简单的web API. 如何从空的项目模板中启 ...

  3. ASP.NET 5系列教程 (四):向视图中添加服务和发布应用到公有云

    向视图中添加服务 现在,ASP.NET MVC 6 支持注入类到视图中,和VC类不同的是,对类是公开的.非嵌套或非抽象并没有限制.在这个例子中,我们创建了一个简单的类,用于统计代办事件.已完成事件和平 ...

  4. ASP.NET MVC3 系列教程 - 目录

    ASP.NET MVC3 系列教程 - 目录   I:ASP.NET MVC3 新增的功能 ASP.NET MVC3 系列教程 - Razor视图引擎基础语法ASP.NET MVC3 系列教程 - V ...

  5. 【ASP.NET Identity系列教程(三)】Identity高级技术

    注:本文是[ASP.NET Identity系列教程]的第三篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...

  6. 【ASP.NET Identity系列教程(一)】ASP.NET Identity入门

    注:本文是[ASP.NET Identity系列教程]的第一篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...

  7. 【ASP.NET Identity系列教程(二)】运用ASP.NET Identity

    注:本文是[ASP.NET Identity系列教程]的第二篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...

  8. Easyui + asp.net MVC 系列教程 第19-23 节 完成注销 登录限制过滤 添加用户

    前面视频 文章地址 Easyui + asp.net MVC 系列教程 第09-17 节 完成登录 高清录制  Easyui + asp.net mvc + sqlite 开发教程(录屏)适合入门  ...

  9. ASP.NET 安全系列 Membership三步曲之入门篇 - Jesse Liu

    Membership 三步曲 ASP.NET 安全系列 Membership三步曲之入门篇 ASP.NET 安全系列 Membership三步曲之进阶篇 ASP.NET 安全系列 Membership ...

随机推荐

  1. ORACLE 分析函数整理汇总

    1. 聚合分析函数 SUM MIN MAX AVG COUNT 这类聚合类分析函数可以在窗口中分组

  2. vi 文字处理器

    vi 的使用 基本上 vi 共分为三种模式,分别是『一般模式』. 『编辑模式』与『指令列命令模式』三种! 这三种模式的作用是: 一般模式: 以 vi 处理一个档案的时后,一进入该档案就是一般模式了.在 ...

  3. (八) 一起学 Unix 环境高级编程 (APUE) 之 信号

    . . . . . 目录 (一) 一起学 Unix 环境高级编程 (APUE) 之 标准IO (二) 一起学 Unix 环境高级编程 (APUE) 之 文件 IO (三) 一起学 Unix 环境高级编 ...

  4. Remoting创建远程对象的一个实例:

    private static Lazy<IChannelManager>  channelManager=new Lazy<IChannelManager>(() =>  ...

  5. Java核心知识点学习----线程中的Semaphore学习,公共厕所排队策略

    1.什么是Semaphore? A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acq ...

  6. php折半查找(数组必须为有序)

    $arr=array('1','7','9','11','20','23','33','44','50');     $len=count($arr);      $low=0;$high=$len- ...

  7. apache的虚拟目录的配置

    第一步:在httpd.conf底部添加以下代码.表示添加虚拟目录 1 <IfModule dir_module> #direcotory相当于是欢迎页面 DirectoryIndex in ...

  8. 浅谈TCP/IP网络编程中socket的行为

    我认为,想要熟练掌握Linux下的TCP/IP网络编程,至少有三个层面的知识需要熟悉: 1. TCP/IP协议(如连接的建立和终止.重传和确认.滑动窗口和拥塞控制等等) 2. Socket I/O系统 ...

  9. 纯css用图片代替checkbox和radio,无js实现方法

    html <ul id="is_offical_post_links"> <li> <label> <input type="c ...

  10. UWP深入学习五: 传感器与搜索、共享及链接

    Responding to motion and orientation sensors: Quickstart: Responding to user movement with the accel ...