Fire server event from client
I am having trouble with the Asp.net page life cycle. I am trying to create a custom menu using HtmlTextWriter with an asp.net LinkButton to fire a server event. I can not get the server event to fire and I get the 'object reference not set to instance of object' when I click my linkbutton. Here is some code.
protected string CreateModuleMenu()
{
var modules = ModuleManager.GetModulesByDeveloperId(Developer.DeveloperID);
StringWriter sw = new StringWriter();
ClientScriptManager cs = Page.ClientScript;
using (HtmlTextWriter writer = new HtmlTextWriter(sw))
{
foreach (var module in modules)
{
writer.RenderBeginTag(HtmlTextWriterTag.Li);
writer.RenderBeginTag(HtmlTextWriterTag.Dl);
writer.RenderBeginTag(HtmlTextWriterTag.Dt);
writer.Write(module.Name);
var files = ModuleManager.GetModuleFilesByModuleId(module.ModuleID);
foreach (var file in files)
{
writer.RenderBeginTag(HtmlTextWriterTag.Dd);
LinkButton lb = new LinkButton();
lb.ID = "mc" + file.ModuleFileID;
lb.Attri开发者_运维百科butes.Add("onclick", cs.GetPostBackEventReference(lb, "LoadControl_Clk"));
lb.Text = file.Name;
Page.RegisterRequiresRaiseEvent(lb);
lb.RenderControl(writer);
writer.RenderEndTag();
}
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderEndTag();
}
}
return sw.ToString();
Here is my click event:
protected void LoadControl_Clk(object sender, EventArgs e)
{
Response.Write("Hello World");
}
Finally here is what I have in the Page_Load event. Note: I tried moving this around to PreRender, PreInt, etc.
protected void Page_Load(object sender, EventArgs e)
{
LiteralControl lit = new LiteralControl();
lit.Text = CreateModuleMenu();
phModuleMenu.Controls.Add(lit);
if (DefaultModuleFile == null)
Response.Write("Error.");
else
{
Control ctrl = LoadControl(DefaultModuleFile.Src);
phAdminModules.Controls.Add(ctrl);
}
}
Lost. Thanks.
Perhaps you need to only load the control in Page_Load on the first time the page is called, that is, if !IsPostBack.
If you load the control on every page load, you will lose the event being fired.
精彩评论