【发布时间】:2011-07-31 01:50:49
【问题描述】:
我构建了自定义 ASP.NET 控件,当我手动(拖放)或通过代码将其添加到标记中的控件时,它工作正常。
自定义控件 MsgBox 嵌入了 JavaScript、CSS 和图像等资源,当我尝试在类中渲染控件以返回其 HTML 代码时出现问题,Page 实例为 null 并且“GetWebResourceUrl”需要它:
Page.ClientScript.GetWebResourceUrl(.....)
有没有办法获取资源网址?这是我的渲染代码:
protected override void RenderContents(HtmlTextWriter writer)
{
using (PlaceHolder plh = new PlaceHolder())
{
if (Page != null)
{
if (DesignMode || Page.Header == null)
RegisterCSSInclude(plh);
}
HtmlGenericControl container = new HtmlGenericControl("div");
container.EnableViewState = false;
container.InnerHtml = "Control html code";
plh.Controls.Add(container);
plh.RenderControl(writer);
}
}
RegisterCSSInclude 是注册我的 css 文件的方法:
private void RegisterCSSInclude(Control target)
{
// CSS
bool linkIncluded = false;
foreach (Control c in target.Controls)
{
if (c.ID == "MsgBxStyle")
{
linkIncluded = true;
}
}
if (!linkIncluded)
{
HtmlGenericControl globalCsslink = new HtmlGenericControl("link");
globalCsslink.ID = "MsgBxGStyle";
globalCsslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl(typeof(MessageBoxCtrl), "MessageBox.MsgBxStyles.WeDevMsgBox.css"));
globalCsslink.Attributes.Add("type", "text/css");
globalCsslink.Attributes.Add("rel", "stylesheet");
globalCsslink.EnableViewState = false;
target.Controls.Add(globalCsslink);
HtmlGenericControl csslink = new HtmlGenericControl("link");
csslink.ID = "MsgBxStyle";
csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl(typeof(MessageBoxCtrl), "MessageBox.MsgBxStyles." + Style.ToString().ToLower() + ".css"));
csslink.Attributes.Add("type", "text/css");
csslink.Attributes.Add("rel", "stylesheet");
csslink.EnableViewState = false;
target.Controls.Add(csslink);
}
}
更新:
PS:我想在通用处理程序 (ashx) 中使用控件,我在其中调用 ShowMsgBox 方法,该方法是类中的方法,而不是页面或用户控件中的方法。
ShowMsgBox 方法应该创建一个 MsgBox 控件的实例并渲染它,然后将 html 代码返回给 ashx 类:
var htmlCode = MyClass.ShowMsgBox("myMsg");
context.Response.write(htmlCode);
【问题讨论】:
标签: c# .net asp.net custom-controls