一、View Components
View Components跟controller(控制器)的功能类似,只有一下几点不同:
1、View Components由template调用,他的输出结果也直接呈现在最后被呈现的网页中。
2、如果 View Components被一个template调用,那么最后呈现的仅仅是这个template<body></body>闭合标签内是内容,不会设计到母板。
3、View Components不一定非要使用template。它可以返回一个string或者stringBuilder由对象生成包含html的对象。
4、只支持一个并且是默认方法,那就是run()。
二、Creating a view component
如果你要创建一个View Components 那么你只需要建立一个类,并且让它继承 ViewComponent即可,当然该类必须包含唯一的默认方法run()。
或者:
请注意,如果run方法没有返回值,或者返回值为null,那么会直接呈现视图,当然视图的名称跟控制器的一模一样,除非你添加了[view(" ")]属性。
由于View Components这些属性和方法跟controller非常类似,所以你也可以定义[BeforeAction] 和 [AfterAction]方法,定义一个特殊的视图去呈现它。
三、Example component
还是看一个例子吧,这样你会更清楚:
这个view component将会呈现在一个testComponent.HTM,viewdata[]定义的变量也可以直接在testComponent.HTM使用,并不可以在调用view component的视图中使用。
如何调用该view component,可以按照下面方法:
四、Component name
默认情况下,Component的名称就是类名,当然你可以改变它,就是通过添加[ComponentName]属性,如下:
五、Javascript in view components
你也可以和controller中一样定义一下javascript。但是你只可以在在main template中定义,为此,一个rootview在components中就显得特别重要了。
六、Ajax in view components
你也可以在components中通过添加ajax[]属性来定义ajax,但是该方法必须是静态的,因为在ajax被调用时,视图已经完全呈现,所以components的作用已经被销毁,除此之外,没有其他影响。
七、Handling postback
View components不是由controller创建,所以它不支持返回值处理。其实名称说明了一切:它适合用来显示数据。
如果你想要创建一个components同时又支持返回值处理,那么你最好是建立一个自定义控件,然后实例化它。因为这些原因,所以在components中不时候进行数据绑定。
未完待续: