ASP.NET 用户控件:无法使用 Eval("...") 初始化用户控件属性

ASP.NET User Control : can#39;t initialize a user control property using Eval(quot;...quot;)(ASP.NET 用户控件:无法使用 Eval(...) 初始化用户控件属性)
本文介绍了ASP.NET 用户控件:无法使用 Eval("...") 初始化用户控件属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I designed a user control. It contains a public property "CurrentValue". When I try to initialize the property using an Eval expression, a null value is assigned.

// In below code, label assignment is OK, RatingNull user control assignment get null

<asp:TemplateField>
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Difficulty") %>'
        <uc1:RatingNull ID="RatingNull1" runat="server" CurrentValue='<%# Eval("Difficulty") %>' />
    </ItemTemplate>

If I directly assigned a value (ie, CurrentValue="5"), user control works fine.

public partial class RatingNull : System.Web.UI.UserControl
{
    private string _CurrentValue;

    public string CurrentValue
    {
        get { return _CurrentValue; }
        set { _CurrentValue = value; }
    }
    (...)
}

解决方案

The following code works for me. When do you use _CurrentValue field?

UserControl

public partial class Test1 : System.Web.UI.UserControl
{

    public string CurrentValue
    {
        get { return (string)ViewState["CurrentValue"] ?? string.Empty; }
        set { ViewState["CurrentValue"] = value; }
    }

    protected override void Render(HtmlTextWriter writer)
    {
        base.Render(writer);

        writer.Write(this.CurrentValue);
    }

}

Page

protected void Page_Load(object sender, EventArgs e)
{
    var ds = new[]
    {
        new { FirstName = "F1", LastName = "L1" },
        new { FirstName = "F2", LastName = "L2" },
    };

    DataList1.DataSource = ds;
    DataList1.DataBind();
}

Html Markup

<asp:DataList ID="DataList1" runat="server">
    <ItemTemplate>
        <uc1:Test ID="Test1" runat="server" CurrentValue='<%# Eval("FirstName") %>' />
    </ItemTemplate>
</asp:DataList>

这篇关于ASP.NET 用户控件:无法使用 Eval("...") 初始化用户控件属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Can I initialize a BCL immutable collection using braces?(我可以使用大括号初始化BCL不可变集合吗?)
The type initializer for #39;System.Data.Entity.Internal.AppConfig#39; threw an exception on a Sub Website(“System.Data.Entity.Internal.AppConfig的类型初始化程序在子网站上引发异常)
Possible to initialize multiple variables from a tuple?(可以从一个元组初始化多个变量吗?)
error loading database initializer with EF6(使用 EF6 加载数据库初始化程序时出错)
How to force fire OnModelCreating every DataContext initialized up(如何强制触发 OnModelCreating 每个初始化的 DataContext)
The type appear in two structurally incompatible initializations within a single LINQ to Entities query(该类型出现在单个 LINQ to Entities 查询中的两个结构不兼容的初始化中)