Quantcast
Channel: Telerik Forums RSS
Viewing all articles
Browse latest Browse all 78072

Binding Grid to AJAX JSON

$
0
0

I have a WebAPI method that is returning a List<User>.  This WebApi is used be several different applications and APIs, but we're attempting our first MVC app against it.  I cannot get the grid to populate unless I add a ModelBinder to the WebAPI to return a DataSourceRequest.  This seems rather counter-intuitive.  It seems the best part of WebAPI is to accept & return generic JSON that anyone can then consume and use.  But by adding the need for the DataSourceRequest, it's no longer a generic API, and will only work with Telerik. (a stretch since the result is just a JSON object with a Data[] holding the actual collection, but either way I just want to use regular ole JSON but still use the Telerik controls.  What if I connect to someone elses API that just returns flat generic JSON?

So what can I do to keep my WebAPI generic, continue using JSON, and yet still have the MVC use the data in it's grid?

Here is the only way I was able to get it to work.

WebAPI Controller:

[HttpGet]
[ActionName("GetAllActiveUsers")]
[EnableCors("*", "*", "GET,POST,PUT,DELETE,OPTIONS")]
publicDataSourceResult GetAllActiveUsers([ModelBinder(typeof(DataSourceRequestModelBinder))] DataSourceRequest request)
{
    List<User> allUsers = _manager.GetAllActiveUsers();
    returnallUsers.ToDataSourceResult(request);
}

 

And here is the Grid/CSHTML Code:

@usingVensure.Dashboard.Data.DatabaseModels
 
@{
    ViewBag.Title = "Index";
}
 
@(Html.Kendo().Grid<User>()
    .Name("ajaxGrid")
    .Columns(cols =>
    {
        cols.Bound(c => c.UserId);
        cols.Bound(c => c.FirstName);
        cols.Bound(c => c.LastName);
        cols.Bound(c => c.UserName);
        cols.Bound(c => c.Email);
    })
    .Scrollable(s => s.Height("auto"))
    .Sortable()
    .Pageable(pageable => pageable
        .Refresh(true)
        .PageSizes(true)
        .ButtonCount(5))
    .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
    .AutoBind(false)
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(r => r
            .Type(HttpVerbs.Get)
        )
        .PageSize(20)
        .ServerOperation(false))
)
 
<script>
    $(function () {
        var grid = $("#ajaxGrid").data("kendoGrid");
 
        grid.dataSource.transport.options.read.beforeSend = function (xhr) {
            xhr.setRequestHeader('X-Access-Token', getCookie('VensureToken'));
        };
 
        grid.dataSource.read();
    });
 
    function getCookie(name) {
        var value = "; "+ document.cookie;
        var parts = value.split("; "+ name + "=");
        if(parts.length == 2) returnparts.pop().split(";").shift();
    }
</script>

 

I tried different things, such s ServerOperation both true and false, etc...


Viewing all articles
Browse latest Browse all 78072

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>