简体   繁体   中英

Null Asp.Net Control Causing Javascript Object reference not set to an instance of an object on render

The sum it up, this code is adding a Jquery Autocomplete to a Textbox inside of an Asp.Net Formview which is inside of an UpdatePanel.

The following code works without any issues unless InsuranceInsertItemTextBox is null, which is always the case when the Formview is in in readonly mode. I tried using an if statement to terminate the function if the control is null, but that doesn't work. I also tried terminating the statement if the Formview Mode is set to readonly, but that didn't work either. Any suggestions on dealing with this error? FYI: LINE 33(identified in stack trace) is the if statement inside of the InitAutoCompl function. If I remove the if statement, the error goes to the next line.

        $(document).ready(function () {
            var prm = Sys.WebForms.PageRequestManager.getInstance();
            prm.add_initializeRequest(InitializeRequest);
            prm.add_endRequest(EndRequest);
             InitAutoCompl();  
        });

        function InitializeRequest(sender, args) {
        }

        function EndRequest(sender, args) {                
            InitAutoCompl();
        }    function InitAutoCompl(freeInput) {

                if (!document.getElementById('<%= CaseInformationFormView.FindControl("InsuranceInsertItemTextBox").ClientID %>'))return;
                $('#<%= CaseInformationFormView.FindControl("InsuranceInsertItemTextBox").ClientID %>').autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            url: '<%= Page.ResolveUrl("PacketsForUpload.aspx/GetInsuranceCompanies") %>',
                            data: "{ 'prefix': '" + request.term + "'}",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            messages: {
                                noResults: '',
                                results: function() {}
                            },
                            success: function(data) {
                                response($.map(data.d, function(item) {
                                    return {
                                        label: item.split("-")[0],
                                        val: item.split("-")[1]
                                    };
                                }));
                            },
                            error: function(response) {
                                alert(response.responseText);
                            },
                            failure: function(response) {
                                alert(response.responseText);
                            }
                        });
                    },
                    change: function(e, ui) {
                        if (!(freeInput || ui.item)) e.target.value = "";
                        Page_ClientValidate();
                    },
                    select: function(e, i) {
                        console.log("i.item", i.item);
                        Page_ClientValidate();
                    },
                    minLength: 3

                });
            };

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
ASP.packetsforupload_aspx.__RenderPacketsHeadContent(HtmlTextWriter __w, Control parameterContainer) in :33
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +268
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +128
System.Web.UI.HtmlControls.HtmlHead.RenderChildren(HtmlTextWriter writer) +21
System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +128
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Control.Render(HtmlTextWriter writer) +10
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +128
System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
System.Web.UI.Page.Render(HtmlTextWriter writer) +29
System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +57
System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1386

EDIT: Additionally, I just figured out that the return will not break the function. I tested this by removing the if statement and just putting a return there. The error still occurs.

If control 'InsuranceInsertItemTextBox' is not as child control of CaseInformationFormView then CaseInformationFormView.FindControl("InsuranceInsertItemTextBox") is null and calling property ClientID will generate the NRE.

You can guard against this condition by checking if the control is available before getting the ClientID:

function InitAutoCompl(freeInput) {
      $('#<%= CaseInformationFormView.FindControl("InsuranceInsertItemTextBox") != null ?CaseInformationFormView.FindControl("InsuranceInsertItemTextBox").ClientID :  "" %>').autocomplete({
        source: function (request, response) {
          $.ajax({
            url: '<%= Page.ResolveUrl("PacketsForUpload.aspx/GetInsuranceCompanies") %>',
            data: "{ 'prefix': '" + request.term + "'}",
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            messages: {
              noResults: '',
              results: function () { }
            },
            success: function (data) {
              response($.map(data.d, function (item) {
                return {
                  label: item.split("-")[0],
                  val: item.split("-")[1]
                };
              }));
            },
            error: function (response) {
              alert(response.responseText);
            },
            failure: function (response) {
              alert(response.responseText);
            }
          });
        },
        change: function (e, ui) {
          if (!(freeInput || ui.item)) e.target.value = "";
          Page_ClientValidate();
        },
        select: function (e, i) {
          console.log("i.item", i.item);
          Page_ClientValidate();
        },
        minLength: 3

      });
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM