【问题标题】:HtmlAnchor.RenderControl throws a NullReference exceptionHtmlAnchor.RenderControl 抛出 NullReference 异常
【发布时间】:2012-10-23 01:05:08
【问题描述】:

我有这段代码

   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

【问题讨论】:

  • temp 为空吗?它断了哪条线?
  • temp 也不为空,它在锚点处中断。RenderControl(writer);

标签: c# asp.net


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    相关资源
    最近更新 更多