簡體   English   中英

ASP.NET Web Forms:如何將列表傳遞給用戶控件?

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

我的網站有帖子類別(例如長篇文章、常見問題解答)。 我試圖兩次顯示指向類別頁面的鏈接列表:在 header 和頁腳中。 所以我制作了一個CategoryList: UserControl和一個 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; }
    }
}

MainMaster.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();

您必須確保根據您放置此代碼的位置,您的事件以正確的順序觸發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM