Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - Why can't I set the asp:Label Text property by calling a method in the aspx file?

Can somebody please explain this to me:

I have a label and I want to be able to set the Text property by calling a method in the aspx file. It works fine if I set the property in code behind, but I really want to set this property in the aspx file.

I have tried a couple of things, but what I expected to work was this:

<asp:Label ID="Label1" runat="server" Text=<%# GetMyText("LabelText") %> />

I get no errors when doing this, but my method is never called and the Text property is left empty.

Is it not possible to set property values to server side controls directly in the aspx without using resources or use hard coded values?

Update: My first try was:

<asp:Label ID="Label1" runat="server" Text=<%= GetMyText("LabelText") %> />

But that results in the following error:

Server tags cannot contain <% ... %> constructs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The syntax =<%# ... %> is Data binding syntax used to bind values to control properties when the DataBind method is called.

You need to call DataBind - either Page.DataBind to bind all the controls on your page, or Label1.DataBind() to bind just the label. E.g. add the following to your Page_Load event handler:

    if (!IsPostBack)
    {
        this.DataBind();
        // ... or Label1.DataBind() if you only want to databind the label
    }

Using Text='<%= GetMyText("LabelText") %>' as others have proposed won't work as you'll find out. This syntax is inherited from classic ASP. It can be used in some circumstances in ASP.NET for inserting dynamic values in static HTML, but can not be used for setting propeties of server controls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...