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

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

9 Answers 3963 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Tomás
Top achievements
Rank 1
Tomás asked on 08 Jul 2014, 08:34 AM
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

9 Answers, 1 is accepted

Sort by
0
Petur Subev
Telerik team
answered on 10 Jul 2014, 07:35 AM
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.

 
0
Mark
Top achievements
Rank 1
answered on 12 Feb 2015, 07:53 PM
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);
        }


0
Mark
Top achievements
Rank 1
answered on 12 Feb 2015, 11:40 PM
Never mind its a typo in my property name. 
0
Matt
Top achievements
Rank 1
answered on 08 Mar 2016, 02:33 PM
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?
0
Dimiter Madjarov
Telerik team
answered on 10 Mar 2016, 08:28 AM

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.

 
0
Digambar
Top achievements
Rank 1
answered on 04 Jan 2017, 05:02 AM
If I want to navigate to another controller action after getting a selected rows in controller using ajax post,then how to navigate ?..
0
Dimiter Madjarov
Telerik team
answered on 04 Jan 2017, 12:18 PM

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.
0
Digambar
Top achievements
Rank 1
answered on 05 Jan 2017, 10:06 AM

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

0
Dimiter Madjarov
Telerik team
answered on 06 Jan 2017, 08:16 AM

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.
Tags
Grid
Asked by
Tomás
Top achievements
Rank 1
Answers by
Petur Subev
Telerik team
Mark
Top achievements
Rank 1
Matt
Top achievements
Rank 1
Dimiter Madjarov
Telerik team
Digambar
Top achievements
Rank 1
Share this question
or