Why <%= %> works in one situation but not in another

后端 未结 6 2133
北恋
北恋 2020-12-28 08:21

This is stemming from a bad answer I gave last night. The curiosity as to why one method works and not the other is bugging me and I\'m hoping someone smarter than me can g

相关标签:
6条回答
  • 2020-12-28 08:53

    Do this on server controls, if you have your LabelText in a Global Resource file:

    <asp:Label ID="Label1" runat="server" Text="<%$ Resources: resourceName, LabelText %>" />
    
    0 讨论(0)
  • 2020-12-28 08:54

    For it to work in the second case, you'd want it as follows:

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

    And then Label1 will need to be databound.

    0 讨论(0)
  • 2020-12-28 09:10

    Using <%= %> is equal to putting Response.Write("") in your page. When doing this:

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

    The ASP.NET processor evaluates the control, then when rendering, it outputs the control's contents & calls Response.Write where it sees <%=.

    In this example:

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

    You can't use Response.Write("") on a Text attribute because it does not return a string. It writes its output to the response buffer and returns void.

    If you want to use the server tag syntax in ASP.NET markup you need to use <%# %>. This combination of markup data binds the value in the tags. To make this work, you'll then need to call DataBind() in your page's Load() method for it to work.

    0 讨论(0)
  • 2020-12-28 09:11

    <%= GetMyText("LabelText") %> basically means

    Response.Write(GetMyText("LabelText"));

    Here it is OK. <%= GetMyText("LabelText") %>

    However when you use this:

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

    It basically means:

    Label1.Text = Response.Write(GetMyText("LabelText"));

    which is a wrong statement.

    0 讨论(0)
  • 2020-12-28 09:15

    Because they are both server side instructions - the second piece of code is equivalent to:

    <asp:Label ID="Label1" runat="server" Text='Response.Write(GetMyText("LabelText"))' />
    
    0 讨论(0)
  • 2020-12-28 09:15

    Wrong format:

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

    Right format with using resources:

    <asp:Label ID="Label1" runat="server" Text='<%$ Resources:Resource, MyText %' />
    
    0 讨论(0)
提交回复
热议问题