Basic Example with asp.net web api and a grid

7 posts, 1 answers
  1. chris
    chris avatar
    13 posts
    Member since:
    Jul 2010

    Posted 20 Aug 2014 Link to this post

    Hi,

    Please can someone help as I cannot get the grid to display any results?

    I have adapted the code from the grid example in the installed demos but cant get it to work. Please see my code below.

    View:

    @(Html.Kendo().Grid<StatusPage.Models.Appliance>()
          .Name("grid")
          .Columns(columns =>
          {
              columns.Bound(p => p.Title);
              columns.Bound(p => p.CurrentStatus).Width(100);
              columns.Command(command => { command.Edit(); command.Destroy(); }).Width(172);
          })
          .ToolBar(tools =>
          {
              tools.Create();
          })
          .Sortable()
          .Pageable()
          .Filterable()
          .DataSource(dataSource =>
              dataSource
                .WebApi()
                .Model(model =>
                {
                    model.Id(p => p.Id);
                })
                .Events(events => events.Error("error_handler"))
                        .Read(read => read.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances" })))
                        .Create(create => create.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances" })))
                        .Update(update => update.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances", id = "{0}" })))
                        .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("Appliance", new { controller = "Appliances", id = "{0}" })))
          )
    )
     
    <script>
    function error_handler(e) {
        var errors = $.parseJSON(e.xhr.responseText);
     
        if (errors) {
            alert("Errors:\n" + errors.join("\n"));
        }
    }
    </script>

    Controller:
    public class AppliancesController : BaseApiController
        {
            public AppliancesController(IRepository repo)
                : base(repo)
            {
            }
     
            public DataSourceResult Get([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
            {
                //var appliances = TheRepository.GetAppliances().ToList()
                //                    .Select(m => TheModelFactory.Create(m));
     
                var appliances = new List<Appliance>() { new Appliance() { Title = "Appliance 1", CurrentStatus = 2 } };
     
                return appliances.ToDataSourceResult(request);
            }
     
            public HttpResponseMessage Get(int appId)
            {
                try
                {
                    var entity = TheRepository.GetAppliance(appId);
                    if (entity == null) return Not_Found();
     
                    return Request.CreateResponse(HttpStatusCode.OK,
                        TheModelFactory.Create(entity));
                }
                catch
                {
                    // TODO logging
                }
     
                return Bad_Request();
            }
     
            public HttpResponseMessage Post([FromBody] Appliance model)
            {
                try
                {
                    if (!ModelState.IsValid) return Bad_Request();
                    model.CurrentStatus = (int)StatusType.Operational;
                    model.LastUpdated = DateTime.Now;
     
                    if (TheRepository.Insert(model) && TheRepository.SaveAll())
                    {
                        return Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(model));
                    }
                }
                catch
                {
                    // TODO logging
                }
     
                return Bad_Request();
            }
     
            [HttpDelete]
            public HttpResponseMessage Delete(int appId)
            {
                try
                {
                    var entity = TheRepository.GetAppliance(appId);
                    if (entity == null) return Not_Found();
     
                    if (TheRepository.DeleteAppliance(entity) && TheRepository.SaveAll())
                    {
                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                }
                catch
                {
                    // TODO logging
                }
     
                return Bad_Request();
            }
     
            [HttpPut]
            [HttpPatch]
            public HttpResponseMessage Patch(int appId, [FromBody] Appliance model)
            {
                try
                {
                    if (!ModelState.IsValid || appId != model.Id)
                        return Bad_Request();
     
                    if (TheRepository.UpdateAppliance(model) && TheRepository.SaveAll())
                    {
                        return Request.CreateResponse(HttpStatusCode.OK);
                    }
                }
                catch (Exception ex)
                {
                    return Bad_Request(ex);
                }
     
                return Bad_Request();
            }
        }

    The grid is displayed and the web api controller GET is being called and is returning the DataSourceResult and no rows are displayed.

    If anyone can help I would be grateful. Thanks in advance.
  2. Rosen
    Admin
    Rosen avatar
    3253 posts

    Posted 22 Aug 2014 Link to this post

    Hello Chris,

    I'm afraid that it is not obvious from the provided details what may be the cause for the issue you are facing. However, could you please verify that you have correctly included the kendo.aspnetmvc.min.js. If you continue to experience difficulties please provide small runnable sample in which the issue can be observed locally.  

    Regards,
    Rosen
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  3. chris
    chris avatar
    13 posts
    Member since:
    Jul 2010

    Posted 22 Aug 2014 in reply to Rosen Link to this post

    Yes, kendo.aspnetmvc.min.js is included. I used the Telerik UI for ASP.NET MVC --> Convert to Telerik Application option.

    I will create an example as you suggest and upload it soon.
  4. chris
    chris avatar
    13 posts
    Member since:
    Jul 2010

    Posted 22 Aug 2014 Link to this post

    This site is crashing when I try to upload the zip of the code
  5. chris
    chris avatar
    13 posts
    Member since:
    Jul 2010

    Posted 22 Aug 2014 Link to this post

    I cannot attach a sample of the code because  the maximum attachment size is (2 MB) !!! Ridiculous!! The solution is 30mb
  6. Answer
    Rosen
    Admin
    Rosen avatar
    3253 posts

    Posted 22 Aug 2014 Link to this post

    Hi,

    I have looked at the sample you have provided via the support ticket and it seems that the issue is caused by the JsonFormatter ContractResolver you have set. As you may know it will change the casing of the serialized objects fields. Thus, they no longer match the configuration set to the Grid and its DataSource. Removing the ContractResolver should address the issue in question.

    Regards,
    Rosen
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  7. chris
    chris avatar
    13 posts
    Member since:
    Jul 2010

    Posted 22 Aug 2014 Link to this post

    Thank you for your help. This solved the issue.
Back to Top