动态更新ASP.net中的UserControl

时间:2015-04-15 23:41:20

标签: asp.net webforms

我是使用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;

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您没有在用户控件中看到更改的值的原因是您所做的任何更改只会进行部分回发。这意味着页面未完全呈现,因此不会呈现您的用户控件。要使用纯ASP.NET webforms创建这样的场景,就是使用更新面板并触发更新。