0

我有这段代码

   var anchor = new HtmlAnchor {HRef = temp, InnerText = this.LinkDescription};
            anchor.Attributes.Add("class", "navActive back");
            anchor.ServerClick += new EventHandler(AnchorServerClick);
            writer.Write("<div id=\"leftnav\"><ul><li>");
            anchor.RenderControl(writer);
            writer.Write("</li></ul></div>");

在自定义 Web 控件中。我在 anchor.RenderControl 处收到 nullReference 异常,为什么?我调试了上面的,作者也不为空,锚也不。那里发生了什么事?谢谢!

编辑:我正在添加堆栈跟踪以进行调试

[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.UI.HtmlControls.HtmlAnchor.GetPostBackOptions() +107
System.Web.UI.HtmlControls.HtmlAnchor.RenderAttributes(HtmlTextWriter writer) +10975634
System.Web.UI.HtmlControls.HtmlControl.RenderBeginTag(HtmlTextWriter writer) +56
System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +26
CER.Portal.Dashboard.Controls.BackLink.Render(HtmlTextWriter writer) +1151
4

1 回答 1

1

查看 GetPostBackOptions 方法的代码,要么需要将 Page 属性设置为当前页面,要么将 CausesValidation 属性设置为 false:

private PostBackOptions GetPostBackOptions()
{
   PostBackOptions options = new PostBackOptions(this, string.Empty) 
   {
      RequiresJavaScriptProtocol = true
   };
   if (this.CausesValidation && (this.Page.GetValidators(this.ValidationGroup).Count > 0))
   {
      options.PerformValidation = true;
      options.ValidationGroup = this.ValidationGroup;
   }
   return options;
}

在 RenderControl 调用之前添加anchor.Page = this.Pageanchor.CausesValidation = false 。

于 2012-10-22T17:05:08.317 回答