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

10 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. 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);
            }


  4. 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. 
  5. Matt
    Matt avatar
    1 posts
    Member since:
    Feb 2016

    Posted 08 Mar 2016 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?
  6. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2205 posts

    Posted 10 Mar 2016 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.

     
  7. Digambar
    Digambar avatar
    4 posts
    Member since:
    Dec 2016

    Posted 03 Jan Link to this post

    If I want to navigate to another controller action after getting a selected rows in controller using ajax post,then how to navigate ?..
  8. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2205 posts

    Posted 04 Jan Link to this post

    Hello Digambar,

    You could redirect to another page in the success event handler of the ajax request via JavaScript.
    E.g.

    $.ajax({
        ...
        success: function (result) {
             window.location.href = "newPage";
        }
    })

    Regards,
    Dimiter Madjarov
    Telerik by Progress
    Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
  9. Digambar
    Digambar avatar
    4 posts
    Member since:
    Dec 2016

    Posted 05 Jan in reply to Dimiter Madjarov Link to this post

    Hi Dimiter Madjarov,

         In MVC 5 View I want to navigate to another controller action after getting a selected rows in controller using ajax post,here selected rows are success fully get in controller But I don't  Navigate to Another View

     

     

    $.ajax({
        ...
        success: function (response) {
        alert(response);
        }
    })

    after post back response alert not show

  10. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2205 posts

    Posted 06 Jan Link to this post

    Hello Digambar,

    From the provided sample code it is not clear what is causing the unexpected behavior. Generally navigating to a new page after an ajax request is not specifically Kendo UI related task, so you could find sample implementations on SO e.g. here or here.

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