当前位置: 移动技术网 > IT编程>开发语言>.net > 解读ASP.NET 5 & MVC6系列教程(14):View Component

解读ASP.NET 5 & MVC6系列教程(14):View Component

2017年12月12日  | 移动技术网IT编程  | 我要评论

油瓶子怕摔,巴伐利亚算法,反恐精英全球攻势中文版下载

在之前的mvc中,我们经常需要类似一种小部件的功能,通常我们都是使用partial view来实现,因为mvc中没有类似web forms中的webcontrol的功能。但在mvc6中,这一功能得到了极大的改善。新版mvc6中,提供了一种叫做view component的功能。

你可以将view component看做是一个mini的controller——它只负责渲染一小部分内容,而非全部响应,所有partial view能解决的问题,你都可以使用view component来解决,比如:动态导航菜单、tag标签、登录窗口、购物车、最近阅读文章等等。

view component包含2个部分,一部分是类(继承于viewcomponent),另外一个是razor视图(和普通的view视图一样)。就像新版mvc中的controller一样,viewcomponent也可以使poco的(即不继承viewcomponent类,但类名以viewcomponent结尾)。

view component的创建

目前,view component类的创建方式有如下三种:

直接继承于viewcomponent给类加上viewcomponent特性,或继承于带有viewcomponent特性的类创建一个类,类名以viewcomponent结尾

和controller一样,view component必须是public的,不能嵌套,不能是抽象类。

举例来说,我们创建一个view component,类名为toplistviewcomponent,代码如下:

public class toplistviewcomponent : viewcomponent
{
 private readonly applicationdbcontext db;

 public toplistviewcomponent(applicationdbcontext context)
 {
 db = context;
 }

 public iviewcomponentresult invoke(int categoryid, int topn)
 {
 list<string> col = new list<string>();
 var items = db.todoitems.where(x => x.isdone == false &&
      x.categoryid == categoryid).take(topn);

 return view(items);
 }
}

上述类,也可以定义成如下这样:

[viewcomponent(name = "toplist")]
public class topwidget
{
 // 其它类似
}

通过在topwidget类上定义一个名称为toplist的viewcomponent特性,其效果和定义toplistviewcomponent类一样,系统在查找的时候,都会认可,并且在其构造函数中通过依赖注入功能提示构造函数中参数的类型实例。

invoke方法是一个约定方法,可以传入任意数量的参数,系统也支持invokeasync方法实现异步功能。

view component的视图文件创建

以在productcontroller的视图里调用view component为例,我们需要在views\product文件夹下创建一个名称为components的文件夹(该文件夹名称必须为components)。

然后在views\product\components文件夹下创建一个名称为toplist 的文件夹(该文件夹名称必须和view component名称一致,即必须是toplist)。

views\product\components\toplist文件夹下,创建一个default.cshtml视图文件,并添加如下标记:

@model ienumerable<bookstore.models.productitem>

<h3>top products</h3>
<ul>
 @foreach (var todo in model)
 {
 <li>@todo.title</li>
 }
</ul>

如果再view component中,没有指定视图的名称,将默认为default.cshtml视图。

至此,该view component就创建好了,你可以在views\product\index.cshtml视图中的任意位置调用该view component,比如:

 <div class="col-md-4">
 @component.invoke("toplist", 1, 10) 
 </div>

如果在上述toplistviewcomponent中定义的是异步方法invokeasync的话,则可以使用@await component.invokeasync()方法来调用,这两个方法的第一个参数都是toplistviewcomponent的名称,剩余的参数则是在toplistviewcomponent类中定义的方法参数。

注意:一般来说,view component的视图文件都是添加在views\shared文件夹的,因为一般来说viewcomponent不会特定于某个controller。

使用自定义视图文件

一般来说,如果要使用自定义文件,我们需要在invoke的方法返回返回值的时候来指定视图的名称,示例如下:

return view("topn", items);

那么,就需要创建一个views\product\components\topn.cshtml文件,而使用的时候则无需更改,还是指定原来的view component名称即可,比如:

@await component.invokeasync("toplist", 1, 10) //以异步调用为例

总结

一般来说,建议在通用的功能上使用view component的功能,这样所有的视图文件都可以放在views\shared文件夹了。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网