ASP.NET Web用户控件的访问内在价值 [英] Accessing inner value of ASP.NET Web User Control

查看:154
本文介绍了ASP.NET Web用户控件的访问内在价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

惊讶的是,我还没有能够找到这个自己,但无论如何。比方说,我用我的网络用户的控制是这样的:

 <我的preFIX:MyTag的用户id =4=服务器>一些花哨的文字< /我的preFIX:MyTag的>

如何将能够访问其codebehind(一些优秀的文本),标签内的文本?期待它通过this.Text,THIS.VALUE或类似的东西暴露出来。

编辑:
我甚至得到网页上的以下警告我在那里尝试用户它:
内容不允许元素MyTag的的开始和结束标记之间。

EDIT2:

 公共部分类MyTag的:用户控件
{
    公众诠释项目编号{搞定;组; }
    保护无效的Page_Load(对象发件人,EventArgs的发送)
    {
    }
}


解决方案

我假设你的自定义控件有文本 string类型称为一个属性。如果再声明这个属性有余辉模式InnerDefaultProperty你应该得到你所期待的。

例如

  ///<总结>
///默认文本属性(内文HTML /标记)
///< /总结>
[PersistenceMode(PersistenceMode.InnerDefaultProperty)
公共字符串PropertyTest
{
    得到
    {
        对象o = this.ViewState [文字];
        如果(O!= NULL)
        {
            回报(字符串)O;
        }
        返回的String.Empty;
    }
    组
    {
        this.ViewState [文字] =值;
    }
}

编辑:
为了避免文字内容不允许你必须加入 [ParseChildren(真的,PropertyTest)] 来您的,以帮助解析器定义(见<一href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.parsechildrenattribute%28VS.80%29.aspx\">MSDN).

当然,你需要一个可写的属性(即它需要一个二传手,我之前省略急促)。

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)
    {           
    }
}

解决方案

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

这篇关于ASP.NET Web用户控件的访问内在价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆