Simple web control isn't rendering properly
I've got a simple web control, which works, sort of. It's just not allowing (no errors though) any variable in the control to be set, whatever I try, it's just not displaying anything apart from default values.
My control:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Message.ascx.cs" Inherits="Message" %>
<asp:Panel runat="server" ID="ErrorPanel">
<asp:Literal
runat="server"
ID="MessageTextLit"
/>
</as开发者_StackOverflow中文版p:Panel>
/// <summary>
/// The type of the message, good, bad etc.
/// </summary>
public enum MessageType
{
Good,
Error
}
public partial class Message : System.Web.UI.UserControl
{
public string MessageText { get; set; } // Text of the error message
public MessageType Type { get; set; } // Message type
protected void Page_Load(object sender, EventArgs e)
{
MessageTextLit.Text = MessageText;
// Set correct CSS class
if (Type == MessageType.Good)
ErrorPanel.CssClass = "good-box";
else if (Type == MessageType.Error)
ErrorPanel.CssClass = "bad-box";
}
}
On my page I have it as:
<CrystalControls:Message runat="server" ID="TopMessage" Visible="false" />
Then when a button is pressed I do:
if (QuestionSubject.Length < 5)
{
TopMessage.MessageText = "Soemthing message";
TopMessage.Type = MessageType.Error;
TopMessage.Visible = true;
}
else if (QuestionBody.Length < 10)
{
TopMessage.MessageText = "Error message";
TopMessage.Type = MessageType.Error;
TopMessage.Visible = true;
}
I've checked, and the if's are firing, it's not throwing any errors, but none of the variables in the Message
class are ever setting! They just default whatever I do. I can't see to change any of their values.
Page_Load is too early to be doing this.
We generally would do this type of thing in OnPreRender, that way if any of your properties get changed during the life-cycle you will pick up the correct values.
protected override void OnPreRender(EventArgs e)
{
MessageTextLit.Text = MessageText; // Set correct CSS class
if (Type == MessageType.Good)
ErrorPanel.CssClass = "good-box";
else if (Type == MessageType.Error)
ErrorPanel.CssClass = "bad-box";
}
精彩评论