How to pass a grid's selected row values to controller

6 posts, 0 answers
  1. Tomás
    Tomás avatar
    5 posts
    Member since:
    Jun 2014

    Posted 08 Jul 2014 Link to this post

    I've got a kendo grid with an image near it that will act like a button. When pressed, it will call a controller method. I want to send the selected row data to that method.

    **VIEW**

    <a href="#" id="ic_open" class="tooltip2" title="Abrir">
        <span title="">
            <img class="toolbar-icons" src="../../Images/open.png"/>
        </span>
    </a>
    ...
    <div id="datagrid">
        @(Html.Kendo().Grid(Model)
            .Name("datagrid_Concessoes")
            .Columns(columns =>
            {
                columns.Bound(c => c.Id).Width(70);
                columns.Bound(c => c.Code);
                columns.Bound(c => c.Description);
                columns.Bound(c => c.CreationDate);
                columns.Bound(c => c.CreationUser);
            })
            .HtmlAttributes(new { style = "height: 534px;" })
            .Scrollable()
            .Sortable()
            .Selectable()
            .Pageable(pageable => pageable
                .Refresh(true)
                .ButtonCount(5))
            .DataSource(dataSource => dataSource
                .Ajax()
                .PageSize(15)
                .Read(read => read.Action("GetConcessoes", "MasterData"))
            )
        )
    </div>


    And the **script**:

    <script type="text/javascript">
     
        $(function () {
     
            $('.tooltip2').click(function () {
     
                var id = this.id;
     
                $.get('@Url.Content("GetPartialView")',
                { "id": id },
                function (data) {
                    $('#div-for-partial').html(data);
                });
     
            });
        });
     
    </script>

    This script sends the link's id (ic_open) to the controller successfully. I want to send the selected row data, via this same function or some other (doesn't matter), to the controller so I can manipulate that info.

    CONTROLLER METHOD

    public ActionResult GetPartialView(string id)
    {
        switch (id)
        {
            case "":
                return PartialView("_Concessoes");
            case "tab1":
                return PartialView("_Concessoes");
            case "tab2":
                return PartialView("_AutoEstradas");
            case "ic_open":
                return PartialView("_NovaConcessao");
     
        }
     
        return RedirectToAction("Index");
     
    }

    Any help?
    Thanks
  2. Petur Subev
    Admin
    Petur Subev avatar
    1882 posts

    Posted 10 Jul 2014 Link to this post

    Hello João,

    You can use the select() method of the Grid to get the selected rows, and the dataItem() of the Grid to get the corresponding JavaScript model which can give you all the information you might need, then with an Ajax request you can send the whole objects or just the IDs to the action method.

    Attached is a small example that sends the whole objects, you can easily modify it and send just the IDs to the server if you need.

    Kind Regards,
    Petur Subev
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  3. UI for ASP.NET MVC is VS 2017 Ready
  4. Mark
    Mark avatar
    4 posts
    Member since:
    Dec 2014

    Posted 12 Feb 2015 in reply to Petur Subev Link to this post

    Hello,
    I was using your sample code and it worked just fine until I moved the code into an MVC Area. Now for some reason the Person[] persons array is null every time.

    Any ideas?

    GRID MarkUp
    @(Html.Kendo().Grid<BatterUp.Web.Areas.AdminTool.Models.OperatorModel>()
                                .Name("OperatorGrid")
                                .DataSource(ds => ds
                                    .Ajax()
                                    .PageSize(5)
                                    .ServerOperation(false) // Paging, sorting, filtering and grouping will be done client-side
                                    .Model(model =>
                                                {
                                                    // the unique identifier (primary key) of the model is the Login ID property
                                                    model.Id(login => login.LoginId);
                                                    model.Field(f => f.LoginId).Editable(false);
                                                })
                                    .Read(read => read.Action("Details", "AdminTool")
                                                        .Data("onAdditionalData")
                                                        )
                                    .Create(create => create.Action("Create", "AdminTool")
                                                        .Data("onAdditionalData"))
                                    .Update(update => update.Action("Edit", "AdminTool"))
                                    .Destroy(destroy => destroy.Action("Delete", "AdminTool"))
                                    //.Events(events =>
                                    //              {
                                    //                  events.RequestEnd("onRequestEnd");
                                    //              })
                                )
                                .Columns(c =>
                                            {
                                                c.Bound(p => p.LoginId)
                                                    .Hidden();
                                                c.Bound(p => p.EmployeeInit);
                                                c.Bound(p => p.Store)
                                                    .Hidden();
                                                c.Bound(p => p.StoreName)
                                                    .Width(450);
                                                c.Bound(p => p.LoginDate);
                                                c.Bound(p => p.MACAddress);
                                                c.Bound(p => p.MachineName);
                                                c.Bound(p => p.DomainUser);
                                                c.Command(command => { command.Edit(); command.Destroy(); })
                                                            .Width(300);
                                            })
                                .ToolBar(commands =>
                                                {
                                                    commands.Create().Text("New AX Operator");
                                                })
                                .Editable(editable =>
                                                {
                                                    editable.Mode(GridEditMode.PopUp);
                                                    editable.Window(w => w.Title("Ax Operator"));
                                                })
                                .Pageable(pager => pager.PageSizes(true)) // Enable paging
                                .Sortable()
                                .Filterable()
                                .Selectable(s => s.Mode(GridSelectionMode.Multiple))
            )

    SCRIPTING
    $('#btn').click(function () {
                    var items = {};
                    var grid = $('#OperatorGrid').data('kendoGrid');
                    var selectedElements = grid.select();
     
                    if (selectedElements.length > 0)
                    {
                        // get user confirmation
                        if (confirm("Are you sure you wish to delete the " + selectedElements.length + " selected Ax Operator IDs?")) {
                            for (var j = 0; j < selectedElements.length; j++) {
                                var item = grid.dataItem(selectedElements[j]);
     
                                items['logins[' + j + '].LOGIN_ID'] = item.LOGIN_ID;
                            }
     
                            $.ajax({
                                type: "POST",
                                data: items,
                                url: '@Url.Action("DeleteSelected", "AdminTool")',
                                success: function (result) {
                                    // call Read to refresh the grid
                                    $("#OperatorGrid").data("kendoGrid").dataSource.read();
                                }
                            })
                        }
                    }
                })

    CONTROLLER ACTION - logins is always null
    public ActionResult DeleteSelected(OperatorModel[] logins, [DataSourceRequest] DataSourceRequest request)
            {
                // make sure there are some to delete
                if (logins != null)
                {
                    foreach (var item in logins)
                    {
                        if (api.EmployeeLoginEFLogic.FindEmployeeLogin(item.LoginId) != null)
                        {
                            api.EmployeeLoginEFLogic.DeleteEmployeeLogin(item.LoginId);
                        }
                    }
     
                    RouteValueDictionary routeValues = this.GridRouteValues();
                    return RedirectToAction("Index", routeValues);
                }
     
                return Json(new[] { logins }.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
            }


  5. Mark
    Mark avatar
    4 posts
    Member since:
    Dec 2014

    Posted 12 Feb 2015 in reply to Mark Link to this post

    Never mind its a typo in my property name. 
  6. Matt
    Matt avatar
    1 posts
    Member since:
    Feb 2016

    Posted 08 Mar in reply to Petur Subev Link to this post

    I ran your demo. First, your "Send to server" button does not actually call the update method on the controller. When I fixed that, I found that the "person" object sent to the controller was always null. Do you have a working example?
  7. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2153 posts

    Posted 10 Mar Link to this post

    Hello Matt,

    If you are referring to the example from my colleague Petur in the second post, it is working as expected on my end. The invoked Controller Action is called Test, which accepts the selected person.

    Regards,
    Dimiter Madjarov
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top
UI for ASP.NET MVC is VS 2017 Ready