オブジェクトのリストの形式でメニューを取得できる場合MenuItem
、各オブジェクトにはサブアイテムの (空の場合もある) リストがあります (つまり、List<MenuItem>
ここでは、このコレクションをデータソースとして使用します。サブリピーターなので、IEnumerable<T>
) をプロパティとして実装する必要がMenuItem.SubItems
あります。おそらく、UserControl
1 つのメニュー レベルをループアウトし、次のメニュー レベルを呼び出す a を使用できます。
には、次のUserControl
ようなものがあります。
<li><a href='<%= this.MenuItem.Url %>'><%= this.MenuItem.LinkText %></a></li>
<asp:Repeater ID="UCRepeater" runat="server">
<HeaderTemplate>
<ul>
<ItemTemplate>
<menu:MenuItem ID="MenuItemUC" runat="server" />
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
のUserControl
はItemTemplate
同じものであるため、各アイテム テンプレートに対して同じものがレンダリングされます。
以下は、このユーザー コントロールのコード ビハインドであり、ここで魔法が起こります。
public partial class MenuItemUserControl : UserControl
{
// A property we'll use as the data source
public MenuItem MenuItem { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
// If the current menu item has sub items, we bind the repeater to them
// And by the way, there is no use doing this on every postback. First
// page load is good enough...
if(!Page.IsPostBack) {
{
if(MenuItem.SubItems.Count > 0)
{
UCRepeater.DataSource = MenuItem.SubItems;
UCRepeater.DataBind();
}
}
}
protected void UCRepeater_OnItemDataBound(object sender,
RepeaterDataBoundEventArgs e)
{
// Every time an Item is bound to the repeater, we take the current
// item which will be contained in e.DataItem, and set it as the
// MenuItem on the UserControl
// We only want to do this for the <ItemTemplate> and
// <AlternatingItemTemplate>
if(e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
var uc = (MenuItemUserControl)e.Item.FindControl("MenuItemUC");
if(uc != null)
{
// This is the magic. Abrakadabra!
uc.MenuItem = (MenuItem)e.DataItem;
}
}
}
}
したがって、これを機能させるために欠けている唯一のものは、データを の階層リストとして取得する優れた方法ですMenuItem
。これはデータ アクセス層に任せます (そして、LINQ to SQL または Entity Framework を使用すると安価で簡単になります... ;))
免責事項: このコードはそのまま提供されており、私は頭のてっぺんから書きました。私はそれをテストしていませんが、うまくいくと思います。うまくいかない場合は、少なくとも問題を解決する方法のアイデアを得ることができます. 問題がある場合は、コメント欄に投稿してください。解決できるように努力しますが、ここでは成功を約束するものではありません。助けたいという気持ちだけです!=)