为什么我无法从其他类(错误)访问MasterPage的公共属性(MessagePlaceholder)?
错误编译器给我的是“错误1找不到类型或命名空间名称'MyMasterPage'(您是否缺少using指令或程序集引用?)”
我的母版页代码
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();
}
}
}
我的错误类
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();
}
}
这就是我设置错误的方法
if (true)
{
Errors.setError("this is an error demo", false);
return;
}
或错误后重定向
if (true)
{
Errors.setError("yet another error", true);
Response.Redirect("~/error.aspx");
}
答案 0 :(得分:0)
尝试这样的事情。
Control FindMe = Page.FindControl("MessagePlaceholder")
if (FindMe != null)
{
((Literal)FindMe).Text = getMessage();
}
放在页面上,(HttpContext.Current.CurrentHandler作为System.Web.UI.Page),或者只是从你的电话中发送Page值。
其他更好的代码。
if(FindMe is Literal)
{
((Literal)FindMe).Text = getMessage();
}