This is a migrated thread and some comments may be shown as answers.

ASP.NET MVC AJAX PartialView Kendo UI Grid onDataBound is not defined error

1 Answer 119 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Robin
Top achievements
Rank 1
Veteran
Robin asked on 09 Feb 2021, 01:25 AM

I  am using a KendoUI treeview. The treeview contain 13 anchor tags . This anchor tags are basically questions. On clicking each Anchor tag, I am making a Ajax call and on Ajax success , I am returning a Partial View as html in the div tag.  The Partial view contains textarea and  KendoUI grid. 
The html is loaded correctly in the div tag with text area and grid .However the console is showing error "Uncaught ReferenceError: onDataBound is not defined"

How do I fix the error ? Should I use Deferred Initialization ?
https://docs.telerik.com/aspnet-mvc/getting-started/helper-basics/fundamentals?&_ga=2.185465772.48909972.1612825511-1665294203.1606507004#deferring-initialization

Also, when I try to test .Read,.Create,.Destroy, .Update, the code does not hit the controller. 

Should I move the javascript code for the KendoUI grid in the PartialView to the global javascript file ?How do I make the Kendo UI grid work in Partial View after Ajax success ? A project with example will be helpful?

Index.cshtml : (Displaying html)

  <div id="divQuestions">

   </div>

 

Ajax Call:

if (id != null) {
        $.ajax({
            type: "POST",
            url: Globals.BaseUrl + "Questions/SaveTocAndShowQuestions/?questionNo=" + tocquestionNo + "&displayNumber=" + tocdisplayNo + "&sectionId=" + SectionId + "&subSectionId=" + SubSectionId,
            dataType: "html",
            async: true,
            cache: false,
            data: serializedForm,
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            success: function (result, textStatus, jqXHR) {
                // window.location.href = result;
               // console.log(result);

                if ($("#divQuestions").length) {
                    $('#divQuestions').html(result);
                                      
                        }
                                          
                    },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Error during process: \n' + ajaxOptions + "," + thrownError + "," + xhr.responseText);
            }

        });

Partial View Containing KendoUI Grid

<div id="pnReporterCommentsGrid">


    @(Html.Kendo().Grid<FYQuestionCommentsInfo>()
         .Name("ReporterCommentGrid")
       
          .Columns(columns =>
          {
              columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
              columns.Bound(m => m.RECORD_TYPE)
                      .Title("Record Type");
              columns.Bound(m => m.RECORDED_DATE).Format("{0:G}")
           .Title("Returned Date");
              columns.Bound(m => m.USERID)
             .Title("Returned By");
              columns.Bound(m => m.COMMENTS)
              .Title("Comments");

          })
        .ToolBar(toolbar => toolbar.Create().Text("Add New Item"))
        .Resizable(resize => resize.Columns(true))
          .Editable(editable => editable.Mode(GridEditMode.PopUp).TemplateName("FYQuestionsCommentsInfo").Window(w => w.Title("Edit").Name("customedit").Width(1000)))
      //    .Events(e => e.Edit("HideGridFields"))
          .Events(e => e.DataBound("onDataBound"))
         .Pageable()
        .Sortable()
        .Scrollable()
         .DataSource(dataSource => dataSource
        .Ajax()

        //  .ServerOperation(false)
        .Events(events => events
        .Sync("RefreshReporterCommentGrid"))
        .Events(events => events.Error("error_handler"))

        .Model(model =>
        {
            model.Id(m => m.QuestionCommentsInfoId);
            model.Field(m => m.QuestionCommentsInfoId).Editable(false);
            model.Field(m => m.USERID).DefaultValue(Model.upacsUserViewModel.Username);
            model.Field(m => m.RECORDED_DATE).Editable(false);

        })
        .Read(read => read.Action("Bind_Reporter", "Questions").Data("sendAntiForgery"))
        .Create(update => update.Action("CreateReporterComments", "Questions").Data("sendAntiForgery"))
         .Destroy(d => d.Action("DestroyReporterComments", "Questions").Data("sendAntiForgery"))
         .Update(update => update.Action("UpdateReporterComments", "Questions").Data("sendAntiForgery"))

     )
    )
</div>

<script type="text/javascript">
        function HideGridFields(e) {

            HideControl("QuestionCommentsInfoId", e);
            HideControl("REGION", e);
            HideControl("STATE_CODE", e);
            HideControl("FiscalYear", e);
            HideControl("REPORT_ID", e);
            HideControl("SECTION_ID", e);
            HideControl("SUBSECTION_ID", e);
            HideControl("QUESTION_NUMBER", e);
            HideControl("QUESTION_PART_NUMBER", e);
            HideControl("DISPLAY_NUMBER", e);
            HideControl("RECORD_TYPE", e);
            HideControl("RECORDED_DATE", e);
            HideControl("QuestionDetailId", e);

        }
        function HideControl(fieldName, e) {
            var cont = $(e.container);
            HideFieldLabel(cont.find("label[for='" + fieldName + "']"));
            HideFieldField(cont.find("#" + fieldName));
        }

        function HideFieldLabel(control) {
            control.parent(".editor-label").hide();
        }

        function HideFieldField(control) {
            control.parent(".editor-field").hide();
        }


        function RefreshReporterCommentGrid() {
            var grid = $('#ReporterCommentGrid').data('kendoGrid');
            grid.dataSource.read();
        }

        function onDataBound(e) {
            var grid = $('#ReporterCommentGrid').data('kendoGrid');
            var gridData = grid.dataSource.view();

            for (var i = 0; i < gridData.length; i++) {
                var currentUid = gridData[i].uid;
                if (gridData[i].RECORDED_DATE != null) {
                    var currenRow = grid.table.find("tr[data-uid='" + currentUid + "']");
                    var editButton = $(currenRow).find(".k-grid-edit");
                    var deleteButton = $(currenRow).find(".k-grid-delete");
                    if (('@Model.upacsUserViewModel.HSIPUserType' == 'SuperReporter') || ('@Model.upacsUserViewModel.HSIPUserType' == 'Reporter'))
                    {
                        if ('@Model.FiscalYear' == '@Constants.Year')
                        {

                            if (gridData[i].RECORD_TYPE == 'Reporter Comments')
                            {
                                editButton.show();
                                deleteButton.show();
                            }
                            else if ((gridData[i].RECORD_TYPE == 'Reviewer Approve Comments') || (gridData[i].RECORD_TYPE == 'Reviewer Return Comments'))
                            {
                                editButton.hide();
                                deleteButton.hide();
                            }
                        }
                        else
                        {
                            editButton.hide();
                            deleteButton.hide();
                        }
                    }
                    else
                    {
                        editButton.hide();
                        deleteButton.hide();
                    }
                }
            }

        }

        function sendAntiForgery() {
            return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }
        }


        function error_handler(e, status) {
            $('#ReporterCommentGrid').data('kendoGrid').cancelChanges();
            if (e.errors) {
                var message = "\n";
                $.each(e.errors, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function () {
                            message += this + "\n";
                        });
                    }
                });
                alert(message);
            }
        }

</script>

 

 

1 Answer, 1 is accepted

Sort by
0
Anton Mironov
Telerik team
answered on 10 Feb 2021, 11:39 AM

Hi Robin,

Thank you for the code snippet and details provided.

As I already answered the same ticket in our private system, will paste the answer here, to share it with the community and will close the other one. Please keep the communication in one place, as it will be easier for tracking and faster resolving.

I am working on resolving both issues for the pointed implementation and could recommend trying the approach from the other ticket first. Try moving the event handlers scripts for the Kendo UI Grid in the global scope(in the Index Page). Observe the result, as the faulty behavior caused by JavaScript errors is resolving to the binding of the Grid, and let me know if the result is the expected one or further assistance is needed.

For further investigation: The fastest route to getting you up and running is if you could provide a runnable, isolated, sample project. Examining this project will let us replicate the issue locally and further troubleshoot it.


Looking forward to hearing back from you.

 

Kind Regards,
Anton Mironov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
Grid
Asked by
Robin
Top achievements
Rank 1
Veteran
Answers by
Anton Mironov
Telerik team
Share this question
or