简体   繁体   English

MVC控制器传递JSON数据,但Kendo Grid不显示它

[英]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. 我在Razor PartialView内运行了一些(动态分配的数量)Kendo网格。 The grids are intended to request their data via AJAX from the MVC controller. 网格旨在通过AJAX从MVC控制器请求其数据。 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). 控制器接收到读取请求,请求很好,然后控制器通过JSON将数据通过JSON传递回线路(通过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. 据我所知,该代码与此场景中的Kendo示例匹配。 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: 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: 控制器对网格1的读取请求的响应:

{"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: 控制器对网格2的读取请求的响应:

{"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: 对网格3的响应

{"Data":[],"Total":0,"AggregateResults":null,"Errors":null} {“ 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. 然后,我添加了动态网格创建(三个网格都使用了传递的模型),它们都显示了所请求的最后一个模型数据,因此我从AJAX方法开始。

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. 之前曾提出过非常类似的问题,但是这些问题都没有向控制器的read函数(正确填充)传递附加值,据我所知,我已经实现了在这些问题和剑道网站没有成功。

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 您可以将Kendo网格中的JSON数据发送到mvc控制器,您需要执行以下步骤

  1. Stringfy Json data and send data through ajax call Stringfy Json数据并通过Ajax调用发送数据
  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); [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. 尝试在控制器操作方法中添加“ JsonRequestBehavior.AllowGet”。 And no need to add "[AcceptVerbs(HttpVerbs.Post)]". 无需添加“ [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);
                }
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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