title: Example of Kendo Grid MVC Wrapper with Web API 2 Controller
body: <p>I'm trying to find an example of a Kendo Grid MVC server wrapper using a Web API 2 controller and not having much luck.  Is there a way to use those server wrappers with the controller generated by VS using "Add" -> "Controller" -> "Web API 2 Controller with actions, using Entity Framework?"  Does using async controller actions affect this?</p>
  
  <p>I've looked at the tutorials at Telerik (<a href="http://docs.telerik.com/kendo-ui/tutorials/asp.net/asp-net-hello-services" rel="nofollow">http://docs.telerik.com/kendo-ui/tutorials/asp.net/asp-net-hello-services</a>) and at the sample project (<a href="http://www.telerik.com/support/code-library/binding-to-a-web-apicontroller-6cdc432b8326" rel="nofollow">http://www.telerik.com/support/code-library/binding-to-a-web-apicontroller-6cdc432b8326</a>), but neither of those are using the new Web API 2 controllers that VS can automatically generate.</p>
  
  <p>I'd prefer to be able to use the VS generated controllers, but my skills are apparently not up to adapting the existing examples to them (this is my first project with MVC/Web API).  Has anyone else done this or should I just write controllers like in those two-year-old examples?</p>
  
  <p><strong>ETA:</strong> Just to include the starting point I've currently got:</p>
  
  <p>I created models using EF Code First from database.  The simple one I'm using to test this with is this one:</p>
  
  <pre><code>namespace TestProject.Models
  {
      using System;
      using System.Collections.Generic;
      using System.ComponentModel.DataAnnotations;
      using System.ComponentModel.DataAnnotations.Schema;
  
      [Table("TP.Industry")]
      public partial class Industry
      {
          public Industry()
          {
              Companies = new HashSet&lt;Company&gt;();
          }
  
          public int IndustryId { get; set; }
  
          public int IndustryCode { get; set; }
  
          [Required]
          [StringLength(150)]
          public string IndustryName { get; set; }
  
          public virtual ICollection&lt;Company&gt; Companies { get; set; }
      }
  }
  </code></pre>
  
  <p>I then created controllers using the "Web API 2 Controller with actions, using Entity Framework" option and checked "Use async controller actions" to get the following controller for that model:</p>
  
  <pre><code>using System;
  using System.Data.Entity;
  using System.Data.Entity.Infrastructure;
  using System.Linq;
  using System.Net;
  using System.Threading.Tasks;
  using System.Web.Http;
  using System.Web.Http.Description;
  using TestProject.Models;
  
  namespace TestProject.Controllers
  {
      public class IndustryController : ApiController
      {
          private TestProjectContext db = new TestProjectContext();
  
          // GET api/Industry
          public IQueryable&lt;Industry&gt; GetIndustries()
          {
              return db.Industries;
          }
  
          // GET api/Industry/5
          [ResponseType(typeof(Industry))]
          public async Task&lt;IHttpActionResult&gt; GetIndustry(int id)
          {
              Industry industry = await db.Industries.FindAsync(id);
              if (industry == null)
              {
                  return NotFound();
              }
  
              return Ok(industry);
          }
  
          // PUT api/Industry/5
          public async Task&lt;IHttpActionResult&gt; PutIndustry(int id, Industry industry)
          {
              if (!ModelState.IsValid)
              {
                  return BadRequest(ModelState);
              }
  
              if (id != industry.IndustryId)
              {
                  return BadRequest();
              }
  
              db.Entry(industry).State = EntityState.Modified;
  
              try
              {
                  await db.SaveChangesAsync();
              }
              catch (DbUpdateConcurrencyException)
              {
                  if (!IndustryExists(id))
                  {
                      return NotFound();
                  }
                  else
                  {
                      throw;
                  }
              }
  
              return StatusCode(HttpStatusCode.NoContent);
          }
  
          // POST api/Industry
          [ResponseType(typeof(Industry))]
          public async Task&lt;IHttpActionResult&gt; PostIndustry(Industry industry)
          {
              if (!ModelState.IsValid)
              {
                  return BadRequest(ModelState);
              }
  
              db.Industries.Add(industry);
              await db.SaveChangesAsync();
  
              return CreatedAtRoute("DefaultApi", new { id = industry.IndustryId }, industry);
          }
  
          // DELETE api/Industry/5
          [ResponseType(typeof(Industry))]
          public async Task&lt;IHttpActionResult&gt; DeleteIndustry(int id)
          {
              Industry industry = await db.Industries.FindAsync(id);
              if (industry == null)
              {
                  return NotFound();
              }
  
              db.Industries.Remove(industry);
              await db.SaveChangesAsync();
  
              return Ok(industry);
          }
  
          protected override void Dispose(bool disposing)
          {
              if (disposing)
              {
                  db.Dispose();
              }
              base.Dispose(disposing);
          }
  
          private bool IndustryExists(int id)
          {
              return db.Industries.Count(e =&gt; e.IndustryId == id) &gt; 0;
          }
      }
  }
  </code></pre>
  
  <p>Finally, I put the following Kendo UI MVC wrapper code in my view for the grid:</p>
  
  <pre><code>@(Html.Kendo().Grid&lt;TestProject.Models.Industry&gt;()
      .Name("Grid")
      .Columns(columns =&gt;
      {
          columns.Bound(c =&gt; c.IndustryId);
          columns.Bound(c =&gt; c.IndustryCode);
          columns.Bound(c =&gt; c.IndustryName);
          columns.Command(c =&gt;
          {
              c.Edit();
              c.Destroy();
          });
      })
      .ToolBar(tools =&gt;
      {
          tools.Create();
      })
      .Sortable()
      .Pageable(pageable =&gt; pageable
          .Refresh(true)
          .PageSizes(true)
          .ButtonCount(5))
      .Filterable()
      .DataSource(dataSource =&gt; dataSource
          .Ajax()
          .Model(model =&gt;
          {
              model.Id(c =&gt; c.IndustryId);
          })
          .Read(read =&gt; read.Url("../api/Industry").Type(HttpVerbs.Get))
          .Create(create =&gt; create.Url("../api/Industry").Type(HttpVerbs.Post))
          .Update(update =&gt; update.Url("../api/Industry").Type(HttpVerbs.Put))
          .Destroy(destroy =&gt; destroy.Url("../api/Industry").Type(HttpVerbs.Delete))
      )
  )
  
  &lt;script&gt;
  
      $(function () {
          var grid = $("#Grid").data("kendoGrid");
  
          // WebAPI needs the ID of the entity to be part of the URL e.g. PUT /api/Product/80
          grid.dataSource.transport.options.update.url = function (data) {
              return "api/Industry/" + data.IndustryId;
          }
  
          // WebAPI needs the ID of the entity to be part of the URL e.g. DELETE /api/Product/80
          grid.dataSource.transport.options.destroy.url = function (data) {
              return "api/Industry/" + data.IndustryId;
          }
      });
  
  &lt;/script&gt;
  </code></pre>
  
  <p>The grid returns no data and request for the api returns this 500 Internal Server Error:</p>
  
  <pre><code>This XML file does not appear to have any style information associated with it. The document tree is shown below.
  &lt;Error&gt;
      &lt;Message&gt;An error has occurred.&lt;/Message&gt;
      &lt;ExceptionMessage&gt;
          The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
      &lt;/ExceptionMessage&gt;
      &lt;ExceptionType&gt;System.InvalidOperationException&lt;/ExceptionType&gt;
      &lt;StackTrace/&gt;
      &lt;InnerException&gt;
      &lt;Message&gt;An error has occurred.&lt;/Message&gt;
      &lt;ExceptionMessage&gt;
          Type 'System.Data.Entity.DynamicProxies.Industry_5BBD811C8CEC2A7DB96D23BD05DB137D072FDCC62C2E0039D219F269651E59AF' with data contract name 'Industry_5BBD811C8CEC2A7DB96D23BD05DB137D072FDCC62C2E0039D219F269651E59AF:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
      &lt;/ExceptionMessage&gt;
      &lt;ExceptionType&gt;
          System.Runtime.Serialization.SerializationException
      &lt;/ExceptionType&gt;
      &lt;StackTrace&gt;
          at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver) at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph) at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at System.Web.Http.WebHost.HttpControllerHandler.&lt;WriteBufferedResponseContentAsync&gt;d__1b.MoveNext()
      &lt;/StackTrace&gt;
      &lt;/InnerException&gt;
  &lt;/Error&gt;
  </code></pre>
  
  <p>In fact, if I just scaffold a view on that model, like this:</p>
  
  <pre><code>@model IEnumerable&lt;TestProject.Models.Industry&gt;
  
  @{
      ViewBag.Title = "Industries";
  }
  
  &lt;h2&gt;Industries&lt;/h2&gt;
  
  &lt;p&gt;
      @Html.ActionLink("Create New", "Create")
  &lt;/p&gt;
  &lt;table class="table"&gt;
      &lt;tr&gt;
          &lt;th&gt;
              @Html.DisplayNameFor(model =&gt; model.IndustryCode)
          &lt;/th&gt;
          &lt;th&gt;
              @Html.DisplayNameFor(model =&gt; model.IndustryName)
          &lt;/th&gt;
          &lt;th&gt;&lt;/th&gt;
      &lt;/tr&gt;
  
  @foreach (var item in Model) {
      &lt;tr&gt;
          &lt;td&gt;
              @Html.DisplayFor(modelItem =&gt; item.IndustryCode)
          &lt;/td&gt;
          &lt;td&gt;
              @Html.DisplayFor(modelItem =&gt; item.IndustryName)
          &lt;/td&gt;
          &lt;td&gt;
              @Html.ActionLink("Edit", "Edit", new { id=item.IndustryId }) |
              @Html.ActionLink("Details", "Details", new { id=item.IndustryId }) |
              @Html.ActionLink("Delete", "Delete", new { id=item.IndustryId })
          &lt;/td&gt;
      &lt;/tr&gt;
  }
  
  &lt;/table&gt;
  </code></pre>
  
  <p>The "@foreach (var item in Model) {" line generates a "NullReferenceException: Object reference not set to an instance of an object." error.</p>
  
  <p>It seems like even if the Kendo part wasn't right, at the very least all of the VS generated code should work correctly and it doesn't seem to be.</p>