Accessing inner value of ASP.NET Web User Control

吃可爱长大的小学妹 提交于 2019-12-08 01:08:18

问题


Surprised that i havent been able to find this myself, but anyway. Let's say i use my web user control like this:

<myprefix:mytag userid="4" runat="server">Some fancy text</myprefix:mytag>

How would i be able to access the text inside the tags from its codebehind ("Some fancy text")? Was expecting it to be exposed through this.Text, this.Value or something similar.

EDIT: I even get the following warning on the page where i try to user it: Content is not allowed between the opening and closing tags for element 'mytag'.

EDIT2:

public partial class mytag: UserControl
{
    public int ItemID { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {           
    }
}

回答1:


I assume your custom control has a property called Text of type string. If you then declare this property to have the persistence mode "InnerDefaultProperty" you should get what you are looking for.

E.g.

/// <summary>
/// Default Text property ("inner text" in HTML/Markup)
/// </summary>
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public string PropertyTest
{
    get
    {
        object o = this.ViewState["Text"];
        if (o != null)
        {
            return (string)o;
        }
        return string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}

Edit: To avoid the "Literal Content Not Allowed" you have to help the parser by adding [ParseChildren(true, "PropertyTest")] to your class definition (see MSDN).

And of course you need a writable property (i.e. it needs a setter which I omitted for shortness before).




回答2:


Just add one line before the class ([ParseChildren(true, "TestInnerText")]), and add a property named "TestInnerText". Create any control of your choice, I have created LiteralControl just to display inner html view.

"TestInnerText" - is just a temporary name I gave, you can use any property name of your choice.

[ParseChildren(true, "TestInnerText")]
public partial class mytag : UserControl
{
    public string TestInnerText
    {
        set
        {
            LiteralControl lc=new LiteralControl();
            lc.Text=value;
            this.Controls.Add(lc);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}


来源:https://stackoverflow.com/questions/2551372/accessing-inner-value-of-asp-net-web-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!