1

如何在没有代码的情况下将方法的输出分配给文本框值?

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    Public TextFromString As String = "test text test text"
    Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w")

    Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer)
        Return New String(Input, Count)
    End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Test Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <%=TextFromString%>
        <br />
        <asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox>
        <br />
        <%=TextFromMethod%>
        <br />
        <asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>        
    </div>   
    </form>
</body>
</html>

这主要是为了让设计师们可以在 aspx 页面中使用它。对我来说,将变量值推送到文本框中似乎是一件简单的事情。

我也很困惑为什么

<asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label>

<asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox>

有效,但

<asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox>

导致编译错误。

4

2 回答 2

2

.ASPX 文件中有几种不同的表达式类型。有:

<%= TextFromMethod %>

它只是保留一个文字控件,并在渲染时输出文本。

然后是:

<%# TextFromMethod %>

这是一个数据绑定表达式,在控件为 DataBound() 时计算。还有表达式构建器,例如:

<%$ ConnectionStrings:Database %>

但这在这里并不重要....

因此,该<%= %>方法不起作用,因为它会尝试将 Literal 插入到 .Text 属性中……显然,这不是您想要的。

<%# %>方法不起作用,因为 TextBox 不是 DataBound,也不是它的任何父项。如果您的 TextBox 位于 Repeater 或 GridView 中,则此方法可行。

那么该怎么办?只是TextBox.DataBind()在某个时候打电话。或者,如果您有 1 个以上的控制权,只需调用Page.DataBind()您的Page_Load.

Private Function Page_Load(sender as Object, e as EventArgs)
   If Not IsPostback Then
      Me.DataBind()
   End If
End Function
于 2008-08-30T18:32:57.993 回答
1

您是否尝试过使用 HTML 控件而不是服务器控件?它是否也会导致编译错误?

<input type="text" id="TextBox4" runat="server" value="<%=TextFromString%>" />
于 2008-08-30T17:15:11.723 回答