How do I make my ASP.NET server control take an embedded code block as a property value?

后端 未结 5 1259
星月不相逢
星月不相逢 2020-12-30 14:07

I have a custom server control with a property of Title. When using the control, I\'d like to set the value of the title in the aspx page like so:



        
相关标签:
5条回答
  • 2020-12-30 14:32

    Note that this is specific to control attributes. When using the <%= syntax outside control attributes meaning anywhere else in the page the syntax works as expected. So this <%=GetCapitalUserName()%>

  • would call the correct method and inject the result of the call in the page.

0 讨论(0)
  • 2020-12-30 14:44

    For the bind property value to work correctly as suggested, you will have this in the aspx or ascx file :

    <cc1:customControl runat="server" Title='<%# PagePropertyValue %>' >
    more content
    </cc1:customControl>
    

    You will then need to actually bind data in your page wich you have to add this in you code behind file (code in C#)

    protected void Page_Load(object sender, EventArgs e)
    {
        DataBind();
    }
    

    That way it will bind the data in your ascx or aspx file.

    0 讨论(0)
  • 2020-12-30 14:50

    As a followup to my own question, I have discovered that what I really wanted was to use ASP.NET Expressions using the <%$ syntax, since what I wanted to do was put in localized content.

    This can be done with apparently no extra handling on the server control side.

    <cc1:customControl runat="server" Title='<%$ Resouces: ResourceFile, ContentKey %>' >
    more content and controls
    </cc1:customControl>
    

    This works just fine.

    0 讨论(0)
  • 2020-12-30 14:52

    You cant. <%= %> will write the string directly to the response-stream, which happens after the server control is constructed. See this post for an explanation.

    So its either codebehind, or <%# + databinding as Zachary suggests.

    0 讨论(0)
  • 2020-12-30 14:52

    Try using databinding syntax: <%# PagePropertyValue %>

    0 讨论(0)
  • 提交回复
    热议问题