This is a migrated thread and some comments may be shown as answers.

Basic Example with asp.net web api and a grid

6 Answers 182 Views
Grid
This is a migrated thread and some comments may be shown as answers.
chris
Top achievements
Rank 1
chris asked on 20 Aug 2014, 03:06 PM
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.

6 Answers, 1 is accepted

Sort by
0
Rosen
Telerik team
answered on 22 Aug 2014, 08:46 AM
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.

 
0
chris
Top achievements
Rank 1
answered on 22 Aug 2014, 09:16 AM
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.
0
chris
Top achievements
Rank 1
answered on 22 Aug 2014, 09:50 AM
This site is crashing when I try to upload the zip of the code
0
chris
Top achievements
Rank 1
answered on 22 Aug 2014, 10:21 AM
I cannot attach a sample of the code because  the maximum attachment size is (2 MB) !!! Ridiculous!! The solution is 30mb
0
Accepted
Rosen
Telerik team
answered on 22 Aug 2014, 12:14 PM
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.

 
0
chris
Top achievements
Rank 1
answered on 22 Aug 2014, 12:55 PM
Thank you for your help. This solved the issue.
Tags
Grid
Asked by
chris
Top achievements
Rank 1
Answers by
Rosen
Telerik team
chris
Top achievements
Rank 1
Share this question
or