tvmannetjie
tvmannetjie

Reputation: 150

Post Kendo Grid data to Controller in MVC

I have two classes. One that contains a list of the other class:

public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public List<Models.Occupation> Occupations { get; set; }

The second class is as follows

public string Name { get; set; }
public string Industry { get; set; }

My controller rendering the view

Person p = new Person()
{
     Name = "megan",
     Surname = "du Preez",
     Id = 0,
     Age = 22
 };
 return View(p);

In the view

@model Models.Person

<form id="person">
    <div>
        @Html.TextBoxFor(mp => mp.Name)
        @Html.TextBoxFor(mp => mp.Surname)
        @(Html.Kendo().Grid<Models.Occupation>()
        .Name("Occupations")
        .Columns(columns =>
            {
                columns.Bound(e => e.Name);
                columns.Bound(e => e.Industry);
            })
        )
        .DataSource(dataSource => dataSource
            .Ajax()
            .Read(read => read.Action("Occupations_Read", "People", new { Name = Model.Name}))
        )
    </div>

    @Html.Kendo().Button().Name("btnTest").Content("Create")

This reads the persons occupations as follows

List<Models.Occupation> oc = new List<Models.Occupation>();
oc.Add(new Models.Occupation() { CategoryName = "Lecturer" });
oc.Add(new Models.Occupation() { CategoryName = "Student" });
oc.Add(new Models.Occupation() { CategoryName = "Janitor" });

return Json(oc.ToDataSourceResult(request));

All this renders my view and it all works, but on the forms post I want to send everything back to the action

[HttpPost]
public JsonResult PersonPost(Models.Person p)
{
    //do stuff
}

I can easily post the Person's name and Surname using the following javascript

$("#btnTest").click(function (e) {
    e.preventDefault();

    $.ajax({
        url: "/Tasks/PersonPost",
        type: 'POST',
        data: $('#person').serialize(),
        dataType: 'json',
        success: function (data) {

        }
    });
});

but the occupations in the grid do not get serialized and posted back to the controller action.

My question is how can I post the whole model with the list of occupations from the view to the controller.

Upvotes: 7

Views: 32407

Answers (4)

Shazhad Ilyas
Shazhad Ilyas

Reputation: 1193

Try this..

    @(Html.Kendo().Grid<Models.Occupation>()
    .Name("Occupations")
    .Columns(columns =>
    {
        columns.Bound(e => e.Name).ClientTemplate("#= Name # <input type='hidden' name='Occupation[#=index(data)#].Name' value='#= Name #' />");
        columns.Bound(e => e.Industry).ClientTemplate("#= Industry # <input type='hidden' name='Occupation[#= index(data)#].Industry' value='#= Industry#' />");
    })        
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read.Action("Occupations_Read", "People", new { Name = Model.Name}))
    )

[HttpPost]
public JsonResult PersonPost(Models.Person p)
{
    //do stuff
}

you should be able to get values in Person. please add the following function.. *****************************Javascript***************************

 //Index function for the WorkOrder Create view
        function index(dataItem) {

            var data = $("#GridName").data("kendoGrid").dataSource.data();
            return data.indexOf(dataItem);
        }

Shaz

Upvotes: 11

Rodolpho Brock
Rodolpho Brock

Reputation: 8165

What about an solution like this:

$( document ).ready(
   $("form").each(function(i, form){
       $(this).find(".k-grid").each(function(_i, div){
           $(form).submit(div, kendoGridSubmitData);
       });
    });
);

function kendoGridSubmitData(e) {
    var lModel = e.data.id;
    var lKendoGrid = $(e.data).data("kendoGrid");

    // Iterate over all rows
    lKendoGrid.dataItems().forEach(function(_row, _rowIndex){
        // Iterate over all fields
        _row.forEach(function(_value, _name){
            // Add the input hidden
            $('<input>').attr({
                type: 'hidden',
                id: lModel,
                name: lModel+'['+_rowIndex+'].'+_name,
                value: _value
            }).appendTo('form');
        });
    });
}

Upvotes: 1

Mohammad Atiour Islam
Mohammad Atiour Islam

Reputation: 5708

You can use this script on your event:

function SaveUserProjectDetails() {

        var postUrl;
        var paramValue;

        var gridData = $("#CustomerInfoKendoGrid").data("kendoGrid").dataSource.data();
        postUrl = '@Url.Content("~/Billing/CustomerAccountManage/GetDepartmentWiseCategoryList")';
        paramValue = JSON.stringify({ CustomerInformationList: gridData });


        $.ajax({
            url: postUrl,
            type: 'POST',
            dataType: 'json',
            data: paramValue,
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                console.log(result);
            },
            error: function (objAjaxRequest, strError) {
                var respText = objAjaxRequest.responseText;
                console.log(respText);
            }
        });

    }

CustomerInformationList is your grid source list. For more details see this

Upvotes: 3

Rahul
Rahul

Reputation: 2307

The grid data isn't in form elements. The form elements appear only when a cell is being edited, then it is removed. You can't post the data to the server by using a form submit button.

The proper way to to this would be by adding the 'save' command button that the grid provides itself:

@(Html.Kendo().Grid<Invoice.Models.ViewModels.SegmentViewModel>()
    .Name("Segment")
    .ToolBar(toolbar => {
        toolbar.Save(); // add save button to grid toolbar
    })
    // ... rest of options ...

Or by calling saveChanges() on the Grid widget:

Save Segments

$("#save").on("click", function () {
    $("#Segment").data("kendoGrid").saveChanges();
});

Upvotes: 3

Related Questions