简体   繁体   中英

MVC controller passing JSON data, but Kendo Grid not displaying it

I have a few (dynamically allocated number) of Kendo grids running inside a Razor PartialView. The grids are intended to request their data via AJAX from the MVC controller. The controller receives the read request, the request is good, and the controller passes the data via JSON back across the wire (verified via Fiddler). Unfortunately, the grid never displays the data. I'm new to this and at a loss regarding where to start. As far as I can tell, the code matches the Kendo examples for this scenario. It's not a data or model problem, as both are used in other parts of the app without issue.

The controller:

public class MemberController : Controller
{
    private MemberContext db = new MemberContext();
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Grid_Member_Read([DataSourceRequest] DataSourceRequest request,
        int club_id)
    {
        var results = from r in db.Members where r.MemberClub.Id == club_id select r;
        return Json(results.ToDataSourceResult(request));
    }
}

The PartialView:

@(Html.Kendo().Grid<RegistrationManagement.Models.Member>()
.Name("MembersGrid")
.Columns(columns =>
{
    columns.Bound(p => p.LastName);
    columns.Bound(p => p.FirstName);
    columns.ForeignKey(p => p.MemberStatusID, (System.Collections.IEnumerable)ViewData["status"], "Value", "Text");
    columns.Bound(p => p.RegistrationYear);
    columns.Bound(p => p.StreetAddress1);
    columns.Bound(p => p.StreetAddress2);
    columns.Bound(p => p.State);
    columns.Bound(p => p.ZipCode);
    columns.Bound(p => p.Email);
    columns.Bound(p => p.PhoneNumber);
    columns.Command(command => { command.Custom("Edit2").Click("CustomEdit"); command.Edit(); command.Destroy(); }).Width(160);

})
        .ToolBar(toolbar => toolbar.Create())
.Editable()
.Groupable()
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(20)
    .Batch(true)
    .ServerOperation(false)
    .Events(events => events.Error("error_handler"))
    .Model(model =>
        {
            model.Id(p => p.Id);
            model.Field(p => p.MemberStatus).Editable(false);
        })
    .Read(read => read
        .Action("Grid_Member_Read", "Member", new { club_id = @ViewBag.ClubID })

    )
    .Create(create => create.Action("Grid_Member_Create", "Member", new { ClubID = @ViewBag.ClubID }))
    .Update(update => update.Action("Grid_Member_Update", "Member"))
    .Destroy(destroy => destroy.Action("Grid_Member_Destroy", "Member"))
 )
)

function error_handler(e) {
    if (e.errors) {
        var message = "Errors:\n";
        $.each(e.errors, function (key, value) {
            if ('errors' in value) {
                $.each(value.errors, function () {
                    message += this + "\n";
                });
            }
        });
        alert(message);
    }
}
function CustomEdit(e) {
    e.preventDefault();

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));

}

The fiddler data:

The controller's response to Grid 1's read request:

{"Data":[{"MemberClub":{"ClubRegion":{"Id":0,"Code":"TE","Name":"Test"},"ClubStatus":       {"Id":0,"Name":"Unknown"},"RelationshipManager":{},"Id":1,"ClubName":"B     Club","RegistrationYear":2000,"StreetAddress1":"street","StreetAddress2":"a","City":"city","State":"state","ZipCode":11111,"PhoneNumber":"555-1212","Email":"a@a.com","URL":"www.w.w."},"MemberStatus":{"Id":2,"Name":"Active"},"Id":1,"MemberClubID":1,"MemberStatusID":2,"MembershipNumberRoot":1,"LastName":"last","FirstName":"Edited","StreetAddress1":"street","StreetAddress2":"a","City":"city","State":"state","ZipCode":"11111","PhoneNumber":"555-1212","Email":"a@a.com","RegistrationYear":2000},{"MemberClub":{"ClubRegion":{"Id":0,"Code":"TE","Name":"Test"},"ClubStatus":{"Id":0,"Name":"Unknown"},"RelationshipManager":{},"Id":1,"ClubName":"B Club","RegistrationYear":2000,"StreetAddress1":"street","StreetAddress2":"a","City":"city","State":"state","ZipCode":11111,"PhoneNumber":"555-1212","Email":"a@a.com","URL":"www.w.w."},"MemberStatus":{"Id":10,"Name":"New"},"Id":10,"MemberClubID":1,"MemberStatusID":10,"MembershipNumberRoot":null,"LastName":"1","FirstName":"1","StreetAddress1":"1","StreetAddress2":"1","City":null,"State":"1","ZipCode":"1","PhoneNumber":"1","Email":"1","RegistrationYear":1},{"MemberClub":{"ClubRegion":{"Id":0,"Code":"TE","Name":"Test"},"ClubStatus":{"Id":0,"Name":"Unknown"},"RelationshipManager":{},"Id":1,"ClubName":"B Club","RegistrationYear":2000,"StreetAddress1":"street","StreetAddress2":"a","City":"city","State":"state","ZipCode":11111,"PhoneNumber":"555-1212","Email":"a@a.com","URL":"www.w.w."},"MemberStatus":{"Id":10,"Name":"New"},"Id":11,"MemberClubID":1,"MemberStatusID":10,"MembershipNumberRoot":null,"LastName":"2","FirstName":"2","StreetAddress1":"2","StreetAddress2":"2","City":null,"State":"2","ZipCode":"2","PhoneNumber":"2","Email":"2","RegistrationYear":2}],"Total":3,"AggregateResults":null,"Errors":null}

The controller's response to Grid 2's read request:

{"Data":[{"MemberClub":{"RelationshipManager":{},"Id":2,"ClubName":"Test Club","RegistrationYear":2000,"StreetAddress1":"street","StreetAddress2":"a","City":"city","State":"state","ZipCode":11111,"PhoneNumber":"555-1212","Email":"a@a.com","URL":"www.w.w.","ClubRegion":{"Id":0,"Code":"TE","Name":"Test"},"ClubStatus":{"Id":0,"Name":"Unknown"}},"MemberStatus":{"Id":10,"Name":"New"},"Id":13,"MemberClubID":2,"MemberStatusID":10,"MembershipNumberRoot":2,"LastName":"Dude","FirstName":"Random","StreetAddress1":"street","StreetAddress2":"a","City":"City","State":"State","ZipCode":"11111","PhoneNumber":"555-1212","Email":"b@b.com","RegistrationYear":2012}],"Total":1,"AggregateResults":null,"Errors":null}

Response to Grid 3:

{"Data":[],"Total":0,"AggregateResults":null,"Errors":null}

(which is correct)

Before I started displaying multiple grids, I had a single grid which used a model passed from the controller to contain the data. That worked perfectly. Then I added the dynamic grid creation (three grids all used a passed model) and they all displayed the last model data requested, so I started with the AJAX approach.

This question is not quite a dupe; very similar questions have been asked before, but none of those are passing an additional value to the controller's read function (which is correctly populated) and, as far as I can tell, I've implemented the changes recommended both in those questions and the Kendo site without success.

This has to be something fundamentally basic. Any ideas?

Thanks!

尝试从ActionMethod中删除[AcceptVerbs(HttpVerbs.Post)]属性

You can send JSON data from Kendo grid to mvc controller You need to follow these steps

  1. Stringfy Json data and send data through ajax call
  2. In the controller receive the data as a list

      var serviceUrl = '/Enrollment/EnrollCourse'; //Pass the items from the grid to the controll. Enroll a user for a course $.ajax({ type: "POST", url: serviceUrl, data: JSON.stringify($("#grid").data("kendoGrid").dataItems()), contentType: "application/json; charset=utf-8", dataType: "json" }).done(function (data, textStatus, request) { alert('success.'); $("#grid").data('kendoGrid').dataSource.data([]); }).fail(function (jqXHR, textStatus, errorThrown) { alert('Error.'); }); 

    [HttpPost] public ActionResult EnrollCourse(IEnumerable enrollments) { return Json(JsonRequestBehavior.AllowGet); }

      Note: Do not try to corrupt JSON data as mentioned by Kendo UI admin data: JSON.stringify({ Technicians:("#Technicians").data("kendoMultiSelect").dataItems() }) 

Try to add "JsonRequestBehavior.AllowGet" in your controller reas action method. And no need to add "[AcceptVerbs(HttpVerbs.Post)]".

            public class MemberController : Controller
            {
                private MemberContext db = new MemberContext();                    
                public ActionResult Grid_Member_Read([DataSourceRequest] DataSourceRequest request,
                    int club_id)
                {
                    var results = from r in db.Members where r.MemberClub.Id == club_id select r;
                    return Json(results.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
                }
            }

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