Sergei F
Sergei F

Reputation: 15

ASP.NET Web Forms: How can I pass a list to a user control?

My website has categories of posts (e.g. longreads, FAQs). I am trying to display a list of links to category pages twice: in the header and in the footer. So I have made a CategoryList : UserControl with a public 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; }
    }
}

On the master page codebehind MainMaster.Master.cs I also have a List<Category> that is set during initialization like

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

Now in MainMaster.Master I try to display this control passing the list to it with an inline data-binding expression:

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

When I run this I get a NullReferenceException in CategoryList.ascx on the line

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

Although when I try to do the same foreach loop on the page MainMaster.Master itself it works alright:

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

But I wouldn't like to repeat exactly the same code twice.
Is there a proper way I can pass a list to a user control?

Upvotes: 0

Views: 712

Answers (1)

mxmissile
mxmissile

Reputation: 11672

Try assigning your categories in code behind, give the control an Id then reference it directly:

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

You should be able to access it in your master page code behind:

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

You will have to make sure depending on where you put this code, that your events fire in the correct order.

Upvotes: 1

Related Questions