简体   繁体   中英

Passing Kendo Grid selected item into Kendo Window

I have got a Kendo Grid with editable records:

在此处输入图片说明

When the user clicks the edit button, a Kendo Window opens with a form to edit the record.

在此处输入图片说明

I am achieving this by filling the Kendo Window from a controller method that fetches the data of the selected record via webservice: <- this is what I want to avoid . Instead, I want to take the data straight out from the table and put it into the input fields inside the Kendo Window, without any additional processing or html calls. The data is already on the table, I just don't know how to send it to the Kendo Window inputs.

Here's some code:

The javascript function called after clicking the edit button:

function openEdit() {
    var window = $("#editWindow").getKendoWindow();
    window.refresh({
        url: '@Url.Action("_EditForm", "Controller")'
    });
    window.center().open();
}

The view contains a partial view call:

@Html.Partial("_EditWindow")

The called partial view contains the Kendo Window:

@(Html.Kendo().Window()
    .Name("editWindow")
    .Modal(true)
    .Events(e => e.Open("drawWindow").Close("refresh").Refresh("hideLoading"))
    .Iframe(true)
    .Visible(false)
    .Title("Edit Record")
)

How can the data from the selected row of the table be passed to the Kendo Window?

EDIT

I know how to get the values from the selected record in javascript:

var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());

I just don't know how to pass them into the Kendo Window inputs.

I came to a solution for my problem. I now send the selected model from the view to the controller. I use the fantastic JSON.stringify to achieve it.

function onChange() {
    if (this.dataItem(this.select()) != null) {
        var rowModel = this.dataItem(this.select());
        // gets the model of the selected item in the grid

        $.ajax({
            url: 'sendGridRecord',
            type: "POST",
            data: JSON.stringify(rowModel),
            contentType: 'application/json'
        });
    }
}

You can define a partial view as per the requirement and render that on a kendow window on edit button click.ie

@(Html.Kendo().Window().Name("myWindow")
      .Content(Html.Partial(@Url.Content("~/Views/_EditWindow.cshtml")).ToString())
      .Visible(false).Title("XYZ").Modal(true).Actions(actions => actions
          .Custom("custom")
          .Minimize()
          .Maximize()
          .Close()
      ).Resizable().Draggable())


function openEdit() {
//Open the kendow window here.
//Get the seleceted item
var grid = $("#grid").data("kendoGrid");
var selectedItem = grid.dataItem(grid.select());
//populate the partial view fields using the selectedItem variable like
$('#name').val(selectedItem.Name);
}

You can use these two methods in order to pass the Kendo().Grid()'s selected row data:


Method I:

.ToolBar(toolbar =>
    {
        toolbar.Template(@<text>
            <div class="toolbar">
                @(Html.Kendo().Button()
                    .Name("myBtn")                        
                    .HtmlAttributes(new { type = "button", @class = "k-primary k-button k-button-icontext", onclick = "callActionBySelectedRowId('#GridMaster')" })  
                    .Content("Add New")
                )
            </div>
        </text>);
    })

function callActionBySelectedRowId(grid) {
    var grid = $(grid).data('kendoGrid');
    id = grid.dataItem(grid.select()).ID;
    window.location.href = '@Url.Action("YourAction", "YourController")/' + id;       
}


Method II:

View:

@(Html.Kendo().Grid<KendoMVCWrappers.Models.Person>().Name("persons")
    .DataSource(dataSource => dataSource
        .Ajax()
                .Model(model =>
                {
                    model.Id(m => m.PersonID);

                })
            .Read(read => read.Action("GetPersons", "Home"))
            .Update(up => up.Action("UpdatePerson", "Home"))
    )
    .Selectable(s => s.Mode(GridSelectionMode.Multiple))
    .Columns(columns =>
    {
        columns.Bound(c => c.BirthDate);
        columns.Bound(c => c.Name);
        columns.Command(cmd => cmd.Edit());
    })
    .Pageable()
    .Sortable()
)

<input type="button" id="btn" name="name" value="send to Server!" />




<script type="text/javascript">
   $(function () {
       $('#btn').click(function () {
           var items = {};
           var grid = $('#persons').data('kendoGrid');
           var selectedElements = grid.select();

           for (var j = 0; j < selectedElements.length; j++) {
               var item = grid.dataItem(selectedElements[j]);
               items['persons[' + j + '].Name'] = item.Name;
                items['persons[' + j + '].PersonID'] = item.PersonID;
           }

           //If you want to pass single item parameter use this and comment out "for loop" & use the second "data" line below:
           //var singleItem = grid.dataItem(selectedElements[0]);

           $.ajax({
               type: "POST",
               data: items,
               //data: { ID: singleItem.ID }, //for passing single item parameter 
               url: '@Url.Action("Test","Home")',
               success: function (result) {
                   console.log(result);
               }
           })
       })
   })


Controller:

public ActionResult Test(Person[] persons)
{
    return Json(persons);
}


Note: If the View called from Controller cannot be rendered use the javascript function as below by using window.location.href instead of $.ajax

<script type="text/javascript">
    $(function () {
        $('#btn').click(function () {
            var items = {};
            var grid = $('#persons').data('kendoGrid');
            var selectedElements = grid.select();
            var item = grid.dataItem(selectedElements[0]);

            window.location.href = '@Url.Action("YourAction", "YourController")/' + item.ID;             
        })
    })
</script>


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM