ViewComponent类继承自ViewComponent抽象类。有3个方法可以重载
- Initialize:用来初始化view component的状态,通常用来核查提供的参数。
- Render:(selects the view or uses another approach to render the component content)选择一个view或者使用
- SupportsSection:指定这个组件可以支持哪些子节点
======HomeController =====
namespace ViewComponentSample.Controllers
{
using System;
using Castle.MonoRail.Framework;
[Layout("default")]
public class HomeController : SmartDispatcherController
{
public void Index()
{
PropertyBag.Add("items",
new String[]
{
"Item 1", "Item 2", "Item 3", "Item 4", "Item 5",
"Item 6", "Item 7", "Item 8", "Item 9", "Item 10",
});
}
}
}
==========StatsComponent ===========
namespace ViewComponentSample.ViewComponents
{
using System;
using Castle.MonoRail.Framework;
public class StatsComponent : ViewComponent
{
private static Random rnd = new Random();
private string pageName;
public override void Initialize()
{
pageName = (String) ComponentParams["pagename"];
base.Initialize();
}
public override void Render()
{
base.Render();
}
}
}
=====statscomponent/default.vm=======
<style type="text/css">
ul.names {
list-style-type: none;
margin:0px;
padding:0px;
}
li.red {
list-style-type: none;
display:block;
margin:0;
padding:2px;
background-color: red;
}
li.black {
list-style-type: none;
display:block;
margin:0;
padding:2px;
background-color: black;
}
#list {
margin:0;
margin-top:10px;
padding:0;
list-style-type: none;
width:250px;
}
#list li {
margin:0;
margin-bottom:4px;
padding:5px;
border:1px solid #888;
cursor:move;
}
</style>
<ul class="names">
#foreach($item in $items)
#odd
<li class="red">$item</li>
#even
<li class="black">$item</li>
#end
</ul>
============home/index.vm=====================
#component(StatsComponent with "pagename='home/index'")