ASP.NET how can access public properties of MasterPage from external Class ?
- by eugeneK
Why i can't access MasterPage's public property (MessagePlaceholder) from other Class (Errors) ?
my master page code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MyMasterPage : System.Web.UI.MasterPage
{
public string MessagePlaceholder
{
get { return messagePlaceholder.InnerHtml; }
set { messagePlaceholder.InnerHtml = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
messagePlaceholder.InnerHtml = Errors.getMessage();
}
}
}
my Errors Class
public static string getMessage()
{
HttpContext c = HttpContext.Current;
string messageType = "";
if (c.Session["errorMessage"] != null)
{
messageType = "errorMessage";
}
else if (c.Session["successMessage"] != null)
{
messageType = "successMessage";
}
if (!string.IsNullOrEmpty(messageType))
{
StringBuilder userMessageSb = new StringBuilder();
userMessageSb.Append(string.Format("<div id=\"{0}\" title=\"{1}\">{2}</div>", messageType, messageType.Replace("Message",string.Empty), c.Session[messageType]));
// fix so message will not re-appear
c.Session.Remove(messageType);
messageType = userMessageSb.ToString();
}
return messageType;
}
public static void setSuccess(string successMessage, bool isRedirect)
{
HttpContext.Current.Session["successMessage"] = successMessage;
}
public static void setError(string errorMessage, bool isRedirect)
{
HttpContext.Current.Session["errorMessage"] = errorMessage;
if (!isRedirect)
{
((HttpContext.Current.CurrentHandler as System.Web.UI.Page).Master as MyMasterPage).MessagePlaceholder = getMessage();
}
}
this is how i set error
if (true)
{
Errors.setError("this is an error demo", false);
return;
}
or with redirect after error
if (true)
{
Errors.setError("yet another error", true);
Response.Redirect("~/error.aspx");
}