New to Telerik UI for ASP.NET MVC? Download free 30-day trial

WebAPI Binding

Web API is an application programming interface for a web application or server which utilizes the HTTP protocol for communication. It enables you to make the server-side of the application more monolithic when it comes to establishing communication between clients and websites to have data access.

For a runnable example, refer to the demo on WebAPI binding of the Scheduler component.

Setting up the application for WebAPI Binding

To ensure that the application is configured for both Web API binding capabilities:

  • Configure Web API by calling GlobalConfiguration.Configure in the Application_Start method.

      public class MvcApplication : System.Web.HttpApplication
      {
          protected void Application_Start()
          {
              GlobalConfiguration.Configure(WebApiConfig.Register);
              RouteConfig.RegisterRoutes(RouteTable.Routes);
          }
      }
    
  • Create a file named WebApiConfig.cs inside the App_Start folder and configure the default WebAPI routing convention.

      public static class WebApiConfig
      {
          public static void Register(HttpConfiguration config)
          {
              // Web API configuration and services.
              // Web API routes.
              config.MapHttpAttributeRoutes();
              config.Routes.MapHttpRoute(
                  name: "DefaultApi",
                  routeTemplate: "api/{controller}/{id}",
                  defaults: new { id = RouteParameter.Optional }
              );
          }
      }
    

Adding a Web API Controller

To support writing and reading data using WebAPI endpoints, the ApiController base class needs to be inherited for a given controller instance.

public class TaskController : System.Web.Http.ApiController
    {
        SchedulerTaskService service;

        public TaskController()
        {
            service = new SchedulerTaskService(new SampleEntities());
        }

        protected override void Dispose(bool disposing)
        {
            service.Dispose();

            base.Dispose(disposing);
        }

        // GET api/task
        public DataSourceResult Get([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
        {
            return service.GetAll().ToDataSourceResult(request);
        }

        // POST api/task
        public HttpResponseMessage Post(TaskViewModel task)
        {
            if (ModelState.IsValid)
            {
                service.Insert(task, null);

                var response = Request.CreateResponse(HttpStatusCode.Created, new DataSourceResult { Data = new[] { task }, Total = 1 });
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = task.TaskID }));
                return response;
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage);

                return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
            }
        }

        // PUT api/task/5
        public HttpResponseMessage Put(int id, TaskViewModel task)
        {
            if (ModelState.IsValid && id == task.TaskID)
            {
                try
                {
                    service.Update(task, null);
                }
                catch (DbUpdateConcurrencyException)
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound);
                }

                return Request.CreateResponse(HttpStatusCode.OK);
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage);
                return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
            }
        }

        // DELETE api/task/5
        public HttpResponseMessage Delete(int id)
        {
            TaskViewModel task = new TaskViewModel
            {
                TaskID = id
            };

            try
            {
                service.Delete(task, null);
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK, task);
        }
    }

Configuring the Scheduler DataSource for Web API Binding

To configure CRUD operations that support Web API Binding, explicitly add a WebApi() configuration method within the DataSource. From there, explicitly specify the WebAPI endpoints by using the Url.HttpRouteUrl() extension method.

Note that a unique identifier for both the Update and Delete operations is passed as a RouteValueDictionary which is then processed on the server-side as an Action Method argument.

@(Html.Kendo().Scheduler<Kendo.Mvc.Examples.Models.Scheduler.TaskViewModel>()
    .Name("scheduler")
    .Date(new DateTime(2022, 6, 13))
    .StartTime(new DateTime(2022, 6, 13, 7, 00, 00))
    .Height(600)
    .Views(views =>
    {
        views.DayView();
        views.WeekView(weekView => weekView.Selected(true));
        views.MonthView();
        views.AgendaView();
        views.TimelineView();
    })
    .Timezone("Etc/UTC")
    .DataSource(d => d
        .WebApi()
        .Model(m =>
        {
            m.Id(f => f.TaskID);
            m.Field(f => f.Title).DefaultValue("No title");
            m.RecurrenceId(f => f.RecurrenceID);
        })
        .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task" })))
        .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task" })))
        .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task", id = "{0}" }))) // Id of the to-be-updated record that will be processed on the server-side.
        .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Task", id = "{0}" }))) // Id of the to-be-deleted record that will be processed on the server-side.
    )
)

See Also

In this article