如何将方法的输出分配给文本框值而无需后面的代码
时间:2020-03-05 18:45:27 来源:igfitidea点击:
如何将方法的输出分配给文本框值而没有后面的代码?
<%@ 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>
导致编译错误。
解决方案
回答
我们是否尝试过使用HTML控件而不是服务器控件?是否还会导致编译错误?
<input type="text" id="TextBox4" runat="server" value="<%=TextFromString%>" />
回答
.ASPX文件中有两种不同的表达式类型。有:
<%= TextFromMethod %>
它仅保留文字控件,并在渲染时输出文本。
然后有:
<%# TextFromMethod %>
这是一个数据绑定表达式,当控件为DataBound()时进行评估。还有表达式构建器,例如:
<%$ ConnectionStrings:Database %>
但这在这里并不是很重要。
因此,<%=%>方法将不起作用,因为它将尝试将Literal插入.Text属性中……显然,这不是我们想要的。
<%%>方法不起作用,因为TextBox不是DataBound,也不是其父级。如果TextBox在Repeater或者GridView中,则此方法将起作用。
那么该怎么办?只要在某个时候调用TextBox.DataBind()
。或者,如果我们有多个控件,则只需在Page_Load中调用Page.DataBind()
。
Private Function Page_Load(sender as Object, e as EventArgs) If Not IsPostback Then Me.DataBind() End If End Function