ASP.NET Web窗体:如何将列表传递给用户控件



我的网站有帖子类别(例如长阅读、常见问题解答(。我尝试两次显示类别页面的链接列表:在页眉和页脚。所以我用一个公共的List<Category>做了一个CategoryList : UserControl

CategoryList.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CategoryList.ascx.cs" Inherits="WebApp.Controls.CategoryList" %>
<% foreach (WebApp.Data.Category c in Categories) // .CategoriesList.Categories.get returned null
{ %>
<span>
<a href="<%= GetRouteUrl("category-view", new { category = c.CategorySlug }) %>">
<%= c.CategoryName %>
</a> <!-- e.g. <a href="/category/longreads">Longreads</a> -->
</span>
<% } %>

CategoryList.ascx.cs:

using System;
using System.Collections.Generic;
namespace WebApp.Controls
{
public partial class CategoryList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e) { }
public List<Data.Category> Categories { get; set; }
}
}

在母版页codebehindMainMaster.Master.cs上,我还有一个List<Category>,它在初始化期间设置,就像一样

public List<Category> Categories { get; } = Data.Categories.All.ToList();

现在,在MainMaster.Master中,我尝试使用内联数据绑定表达式显示将列表传递给它的控件:

<%@ Register TagPrefix="custom" TagName="CategoryList" Src="~/Controls/CategoryList.ascx" %>
<!-- HTML form opening -->
<custom:CategoryList Categories="<%# Categories %>" runat="server" />
<!-- HTML form closing -->

当我运行这个时,我在线上的CategoryList.ascx中得到一个NullReferenceException

foreach (WebApp.Data.Category c in Categories) // .CategoriesList.Categories.get returned null

尽管当我尝试在页面MainMaster.Master上执行相同的foreach循环时,它工作正常:

<!-- HTML form opening -->
<% foreach (WebApp.Data.Category c in Categories) // MainMaster.Categories
{ %>
<span>
<a href="<%= GetRouteUrl("category-view", new { category = c.CategorySlug }) %>">
<%= c.CategoryName %>
</a>
</span>
<% } %>
<!-- HTML form closing -->

但我不想重复两次完全相同的代码
是否有适当的方法可以将列表传递给用户控件?

尝试在代码后面分配类别,给控件一个Id,然后直接引用它:

<custom:CategoryList runat="server" id="categoryList" />

你应该能够在你的主页代码后面访问它:

categoryList.Categories = Data.Categories.All.ToList();

您必须确保根据您将此代码放在的位置,您的事件以正确的顺序启动。

最新更新