为什么我不能设置ASP:标签Text属性通过调用aspx文件的方法? [英] Why can't I set the asp:Label Text property by calling a method in the aspx file?

查看:78
本文介绍了为什么我不能设置ASP:标签Text属性通过调用aspx文件的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人请给我讲解一下:

我有一个标签,我希望能够通过调用aspx文件的方法来设置Text属性。如果我设置code中的财物的,但我真的想设置在aspx文件这个属性,它工作正常。

我已经尝试了几件事情,但我希望的工作是这样的:

 < ASP:标签ID =Label1的=服务器文本=<%#GetMyText(LabelText的)%> />

这样做的时候我没有错误,但我的方法不会被调用和Text属性为空。

这难道不是可能的属性值直接在ASPX设置为服务器端控件,而无需使用资源或使用硬codeD值?

更新:我的第一次尝试是:

 < ASP:标签ID =Label1的=服务器文本=<%= GetMyText(LabelText的)%> />

但是,这会导致以下错误:


  

服务器标记不能包含<%...%>构造



解决方案

语法= LT;%#...%>是数据绑定语法的用于绑定值来控制属性时调用DataBind方法被调用。

您需要调用DataBind - 要么的Page.DataBind所有控件绑定您的网页上,或Label1.DataBind()只是标签绑定。例如。以下添加到您的Page_Load事件处理程序:

 如果(!的IsPostBack)
    {
        this.DataBind();
        // ...或Label1.DataBind()如果你只想数据绑定标签
    }

使用文本='<%= GetMyText(LabelText的)%>'为他人已经提出将无法正常工作,你会发现。这个语法是从传统的ASP继承。它可以在在ASP.NET某些情况下是用于插入在静态HTML的动态值,但不能被用于设置服务器控件化子性质

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.

解决方案

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.

这篇关于为什么我不能设置ASP:标签Text属性通过调用aspx文件的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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