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

KendoUI Grid in Partial View after Ajax Success returns Empty Grid

1 Answer 14 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, 02:12 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 KendoUI grid. 
When the partial view is rendered, it only displays an empty grid without data in it.

How do I get it to work in Partial View 

However the console is showing error "Uncaught ReferenceError: onDataEdit is not defined"

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

<div id="pvRHCPGridQuestion7">

    <p><b>Input the number of crossings and program emphasis areas by crossing type.</b></p>

    @Html.AntiForgeryToken()

    @(Html.Kendo().Grid<HSIP.Domain.Grid7DomainModel>()
                  .Name("PerformanceGrid")
                  .Columns(columns =>
                  {
                      columns.Bound(m => m.display_num).Hidden();
                      columns.Bound(m => m.FIXED_ROWS).Hidden();
                      columns.Bound(m => m.MAX_ROW_NUM).Hidden();
                      columns.Command(command => { command.Destroy(); }).Width("20%");
                      //columns.Command(command =>
                      //{
                      //    command.Custom("Delete").Click("onDataRemove").SendDataKeys(true);
                      //}).Width("20%");
                      columns.Bound(m => m.val_description).Title("Crossing Type").HtmlAttributes(new { style = "text-align: left;" }).HeaderHtmlAttributes(new { style = "text-align: center;" });
                      columns.Bound(m => m.col1).EditorTemplateName("IntegerBox").HtmlAttributes(new { style = "text-align: right;" })
                      .Title("Number of Crossings").HeaderHtmlAttributes(new { style = "text-align: center;" });

                  })
    .ToolBar(toolbar => {
        toolbar.Create().Text("Add New Item");
        toolbar.Save().CancelText("Undo");
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Resizable(resize => resize.Columns(true))
    .Events(events => events.Edit("onDataEdit").Save("onDataSave").SaveChanges("onSaveChanges"))
    .DataSource(dataSource => dataSource
    .Ajax()
    .Batch(true)
    .ServerOperation(false)
    .Events(events => events.Error("error_handler"))
    .Events(events => events.Sync("RefreshGrid"))
    .Model(model =>
    {
        model.Id(m => m.display_num);
        model.Field(m => m.display_num).Editable(false);
        model.Field(m => m.val_description).Editable(true);
        model.Field(m => m.col1).Editable(true);
        model.Field(m => m.FIXED_ROWS).Editable(false);
        model.Field(m => m.MAX_ROW_NUM).Editable(false);

    })
    .Sort(sort => sort.Add("display_num").Ascending())
    .Create(update => update.Action("Create_Q7_Batch", "Questions").Data("sendAntiForgery"))
    .Read(read => read.Action("Bind_Q7", "Questions").Data("sendAntiForgery"))
    .Update(update => update.Action("Update_Q7_Batch", "Questions").Data("sendAntiForgery"))
    .Destroy(d => d.Action("Destroy_Q7_Batch", "Questions").Data("sendAntiForgery"))
    )

    )

</div>

<script type="text/javascript">

function sendAntiForgery() {
        return { "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }
    }
   
    function onDataRemove(e) {
        e.preventDefault();
        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        if (confirm('Are you sure you want to clear the values?')) {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("CustomDelete_Q7", "Questions")',
                data: { display_num: dataItem.display_num },
                dataType: "text",
                traditional: true,
                async: false,
                success: function (s) {
                    if (s.ErrorDetails) {
                        alert(s.ErrorDetails);
                    } else {
                        $('#PerformanceGrid').data("kendoGrid").dataSource.read();
                    }
                },
                error: function (s) {
                    if (s.ErrorDetails) {
                        alert(s.ErrorDetails);
                    }
                }
            });
        }
    };

function onSaveChanges(e) {
        var errors = [];
        var dataSource = $('#PerformanceGrid').data("kendoGrid").dataSource;
        var rows = dataSource.data();
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].dirty) {
                if ((rows[i].FIXED_ROWS == null || (rows[i].id != null && rows[i].id > rows[i].FIXED_ROWS)) && rows[i].val_description != null && rows[i].val_description.length > 100) {
                    alert("Maximum length for Performance Measure is 100!");
                    e.preventDefault();
                    return;
                }
            }
        }

        var validRows = 0;
        for (var i = 0; i < dataSource.data().length; i++) {
            if (rows[i].dirty) {
                if (isNaN(parseInt(rows[i].col1)) == false) {
                    validRows++;
                }
            }
            else {
                validRows++;
            }
        }
        if (validRows < dataSource.data().length) {
            e.preventDefault();
            alert('Please complete "NUMBER OF CROSSING" for all rows.');
        }
    }

    function onDataSave(e) {
    if (e.values.val_description) {
        if ((e.model.isNew() || e.model.id > e.model.FIXED_ROWS) && e.values.val_description.length > 100) {
            alert("Maximum length for Performance Measure is 100!");
        }
    }
    }

    function onDataEdit(e) {
        $(".field-validation-valid").empty();
         if (e.model.isNew()) {

        }
        else {
            if (e.model.id <= e.model.FIXED_ROWS) {
                e.container.find("input[name='val_description']").each(function () { $(this).attr("disabled", "disabled") });
            }
        }

         //$('#col1').kendoNumericTextBox({decimals:0, format: '#', min:0});
    }

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

    function error_handler(e, status) {
        $('#PerformanceGrid').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, 10:17 AM

Hello Robin,

Thank you for the provided code snippets and details.

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 dived deeply into your implementation and assume that the event handlers are positioned in the Partial View. The Grid component is initialized when the scripts are not yet loaded. Move the event handler scripts into the Index page and observe the result.

Let me know if the result is the expected one, or further assistance is needed.

After making these changes, have a look into the Developer Tools Console for new errors. Let me know what is the new behavior and I will try my best to assist with resolving the issue if it persists.

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