【发布时间】:2015-04-15 23:41:20
【问题描述】:
我是使用 ASP.net WebForms 的新手,我正在尝试动态更新添加到占位符的 UserControl。我正在处理的示例没有更新,尽管事件“onTextChanged”正在被触发。欢迎任何指示/建议。
WebForm1.aspx
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
MasterPageFile="~/Site.Master" CodeBehind="WebForm1.aspx.cs" Inherits="FFUC.WebForm1" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:Panel runat="server" ID="configPanel" Visible="true">
Book Title:<asp:TextBox ID="tbxBookTitle" runat="server" OnTextChanged="updateBookTitle" AutoPostBack="true"></asp:TextBox>
Book Author:<asp:TextBox ID="tbxBookAuthor" runat="server" OnTextChanged="updateBookAuthor" AutoPostBack="true"></asp:TextBox>
</asp:Panel>
<asp:Panel ID="UpdatePanel1" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
</asp:Panel>
</asp:Content>
WebForm1.aspx.cs
namespace FFUC
{
public partial class WebForm1 : System.Web.UI.Page
{
private UC.WebUserControl1 ctrl1;
protected void Page_Load(object sender, EventArgs e)
{
// Add the control to the page
ctrl1 = (UC.WebUserControl1)Page.LoadControl("UC/WebUserControl1.ascx");
PlaceHolder1.Controls.Add(ctrl1);
}
protected void updateBookTitle(object sender, EventArgs e)
{
ctrl1.BookTitle = tbxBookTitle.Text;
}
protected void updateBookAuthor(object sender, EventArgs e)
{
ctrl1.BookAuthor = tbxBookAuthor.Text;
}
}
}
WebUserControl1.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"
Inherits="FFUC.UC.WebUserControl1" %>
<h>Books:</h><br />
<asp:Literal runat="server" ID="lblBookTitle" Text="default" Visible="true"></asp:Literal>
<asp:Literal runat="server" ID="lblBookAuthor" Text="default" Visible="true"></asp:Literal>
WebUserControl1.ascx.cs
namespace FFUC.UC
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
private string bookTitle = "book title";
public string BookTitle { get; set; }
private string bookAuthor = "book author";
public string BookAuthor { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
lblBookAuthor.Text = BookAuthor;
lblBookTitle.Text = BookTitle;
}
}
}
【问题讨论】:
-
经验法则: ASP.NET 代码背后的事件是服务器端代码;它们在回发发生之前不会执行。要在没有回发的情况下在客户端上发生某些事情,您需要使用 Javascript。
-
问题是该控件是在运行时动态添加的——那么除了服务器端代码之外,我如何引用它?
-
如果代码没有执行,你怎么知道
OnTextChanged事件被触发了? -
代码执行,但我通过“配置”所做的更改并未更新 userControl。无论如何,我认为这是一个设计糟糕的示例,所以我将结束这个问题。