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

Kendo Grid datasource binding after server postback

6 Answers 1545 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jonathan
Top achievements
Rank 1
Jonathan asked on 10 Jul 2018, 07:48 PM

I have a Kendo Grid and would like to bind to the server-side WebAPI call result after the postback. The Grid result is based upon the selected dropdown value when the submit button is clicked. I am able to invoke the button click event, bind the webapi result to the Input.PermitList JSON result  attribute. But the Grid is still empty. Anything I might have missed? Please suggest

Front-end code

 <form method="post">
    <h2>Permits</h2>
    <div>
        <label asp-for="Input.PermitCategoryList" class="control-label"></label>
        <kendo-dropdownlist name="categories" for="@Model.Input.PermitCategory"
                            option-label="Select permit Category..."
                            class="form-control"
                            bind-to="@(new SelectList(@Model.Input.PermitCategoryList,"Alias","Name"))"></kendo-dropdownlist>
        <span asp-validation-for="Input.PermitCategoryList" class="text-danger"></span>
    </div>
    <div>
        <button name="btnGetPermit" icon="filter" type="submit" asp-page-handler="PermitList" class="k-button">Get Permits</button>
    </div>

    <div>
        <h4>Permits</h4>
        <kendo-grid name="grid" height="550" datasource-id="dataSource">
            <groupable enabled="true" />
            <sortable enabled="true" />
            <pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
            </pageable>
            <filterable enabled="true" />
            <columns>
                <column field="Id" title="Permit Id" />
                <column field="Class" title="Permit Class" />
                <column field="Name" title="Permit Name" />
                <column field="Type" title="Permit Type" />
                <column field="Fee" title="Permit Fee" />
            </columns>
        </kendo-grid>
    </div>

    <script>
    var data = @LITSPermitting.Admin.Extensions.JavaScriptConverter.SerializeObject(Model.Input.PermitList);

    var dataSource = new kendo.data.DataSource({
        data: data,
        pageSize:5
    })
    </script>
</form>

Back-end Button click event

        [BindProperty]
        public InputModel Input { get; set; }

        public class InputModel
        {
            [Required]
            [Display(Name = "Permit Category")]
            public List<PermitCategoryDto> PermitCategoryList { get; set; }

            public string PermitCategory { get; set; }

            public JsonResult PermitList { get; set; }
        }

 

        /// <summary>
        /// Get a list of Permits based upon the category request
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ActionResult> OnPostPermitListAsync([DataSourceRequest]DataSourceRequest request)
        {
            await HttpContext.Session.LoadAsync();
            Input.PermitCategoryList = HttpContext.Session.Get<List<PermitCategoryDto>>(Constants.PERMIT_CATEGORY_LIST);

            //tp is the temporary permit type
            string requestUri = Constants.PERMIT_CATEGORY_REQUEST_URI + Input.PermitCategory;

            _response = await _client.GetAsync(requestUri);
            if (_response.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api     
                var result = _response.Content.ReadAsStringAsync().Result;

                //Deserializing the response recieved from web api and storing into the Permit list    
                var drResult = JsonConvert.DeserializeObject<List<PermitDto>>(result);

                Input.PermitList=new JsonResult(drResult.ToDataSourceResult(request)); 
                return Input.PermitList;
            }
            else
            {
                return NotFound();
            }

        }

 

 

6 Answers, 1 is accepted

Sort by
0
Viktor Tachev
Telerik team
answered on 13 Jul 2018, 01:57 PM
Hi Jonathan,

Based on the provided description I guess that the Grid will not show data initially. When the users select an item from the DropDownList and click the button then the Grid should show the relevant records. Please correct me if I have misunderstood the scenario.

In order to implement the behavior I would suggest setting the autoBind option for the Grid to false. When the users click the button handle its client-side click event and call the read() method for the Grid DataSource. This way the Grid will fire a request to retrieve its data. The value from the DropDownList can be passed as additional information either directly in the read() method or by defining a Data() handler for the Grid Read action. 


Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Jonathan
Top achievements
Rank 1
answered on 16 Jul 2018, 12:46 PM

Viktor, 

Thank you for your reply. Yes, the Grid will not show the data initially until the user clicks the submit button. And we would like to handl the button click event on server side, not client side based on some security concerns from DMZ web front-end. Is there any small example available how to trigger or call the Grid DataSource read() method from the server after postback?

0
Viktor Tachev
Telerik team
answered on 18 Jul 2018, 09:54 AM
Hello Jonathan,

Please have in mind that the Grid component is a client-side widget. The .NET Core wrapper provides the option to use TagHelpers to define the component, however that is serialized to the client as Kendo UI grid. Thus, there is no server-side read method for DataSource.

Nevertheless, what I can suggest to avoid calling read() from the client is to generate the Grid on the client based on the data returned from the server. When the button submits the user selection return a relevant information from the server that can be used to generate the Grid like illustrated in the following blog post. 




Regards,
Viktor Tachev
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Jonathan
Top achievements
Rank 1
answered on 20 Jul 2018, 08:32 PM

Thank you Viktor for your reply. I have followed the example and re-write my program with Kendo Grid JQuery style. I am able to create button click event and capture the dropdown selected value to call the ASP.NET Razor Page model class like below.

        $('#btnDisplayGrid').click(function () {
            var selectCategoryValue = document.getElementById('Input.PermitCategory').value;
            createGrid("permits", "/Permit/PermitEditableGrid?handler=PermitList&category=" + selectCategoryValue);
        });

 

I am currently working on the Grid Update() method and how should I pass the data to the page handler and bind to the parameter? Any suggestions?

Kendo Grid - update

=======================

                    update: {                        
                        url: "/Permit/PermitEditableGrid?handler=UpdatePermit",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader('XSRF-TOKEN', $('input:hidden[name="__RequestVerificationToken"]').val());
                        }
                    },

 

ASP.NET Razor page code-behind - 

======================================

[ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<ActionResult> OnPostUpdatePermitAsync([FromBody]PermitDto permitDto)
        {
            //await HttpContext.Session.LoadAsync();
            //Input.PermitCategoryList = HttpContext.Session.Get<List<PermitCategoryDto>>(Constants.PERMIT_CATEGORY_LIST);
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

......

 

 

 

0
Georgi
Telerik team
answered on 25 Jul 2018, 02:21 PM
Hello Jonathan,

I have investigated the provided configuration and noticed that the name of  handler in the url is UpdatePermit but the handler is called OnPostUpdatePermitAsync.

Could you please try to modify the url as below and let me know if the updated item is sent to the server as expected?


url: "/Permit/PermitEditableGrid?handler=UpdatePermitAsync",


Regards,
Georgi
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.

0
Jonathan
Top achievements
Rank 1
answered on 02 Aug 2018, 12:37 PM

Georgi,

Thank you for your suggestion. I am under the impression that named handler methods are created by taking the text in the name after On<HTTP Verb> and before Async (if present).I changed the datasource from Ajax to WebApi and re-name page method to  OnPutUpdatePermitAsync and I could debug the program and the handler method breakpoint is hitted. 

        @(Html.Kendo().Grid<LITSPermitting.Models.PermitDto>()
                .Name("grid")
                .Columns(columns =>
                {
                    columns.Bound(p => p.Class).Title("Permit Class").Width(100);
                    columns.Bound(p => p.Name).Title("Permit Name").Width(100);
                    columns.Bound(p => p.Fee).Title("Permit Fee").Format("{0:c}").Width(100);
                    columns.Bound(p => p.Type).Title("Permit Type").Width(100);
                    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(150);
                })
                .ToolBar(toolbar => toolbar.Create())
                .Editable(editable => editable.Mode(GridEditMode.InLine))
                .Pageable()
                .Sortable()
                .AutoBind(false)
                .Scrollable()
                .HtmlAttributes(new { style = "height:650px;" })
                .DataSource(dataSource => dataSource.WebApi()
                    .PageSize(20)
                    .Events(events => events.Error("error_handler"))
                    .Model(model => model.Id(p => p.Id))
                    .Create(create => create.Action("PermitInlineEditor", "Permit", new { handler = "CreatePermit" }).Data("sendAntiForgery"))
                    .Read(read => read.Action("PermitInlineEditor", "Permit", new { handler = "PermitList" }).Data("filterPermits"))
                    .Update(update => update.Action("PermitInlineEditor", "Permit", new { handler = "UpdatePermit" }).Data("sendAntiForgery"))
                    .Destroy(delete => delete.Action("PermitInlineEditor", "Permit", new { handler = "DeactivatePermit" }).Data("sendAntiForgery"))
                )
        )

 

        [ValidateAntiForgeryToken]
        [HttpPut]
        public async Task<ActionResult> OnPutUpdatePermitAsync([DataSourceRequest] DataSourceRequest request, PermitDto permitDto)
        {
            if (permitDto ==null || !ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

    .......

}

 

Tags
Grid
Asked by
Jonathan
Top achievements
Rank 1
Answers by
Viktor Tachev
Telerik team
Jonathan
Top achievements
Rank 1
Georgi
Telerik team
Share this question
or