【问题标题】:ASP.NET Web Forms: How can I pass a list to a user control?ASP.NET Web 窗体:如何将列表传递给用户控件?
【发布时间】:2021-03-11 17:13:05
【问题描述】:

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

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; }
    }
}

在母版页代码隐藏MainMaster.Master.cs 上,我还有一个List&lt;Category&gt;,它在初始化期间设置,例如

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 -->

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

【问题讨论】:

    标签: c# asp.net webforms dry


    【解决方案1】:

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

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

    您应该可以在后面的母版页代码中访问它:

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

    您必须确保根据您放置此代码的位置,您的事件以正确的顺序触发。

    【讨论】:

      猜你喜欢
      • 2018-07-26
      • 2010-09-20
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      相关资源
      最近更新 更多