Telerik blogs

With the introduction of MVC 4 Microsoft has created a fantastic new way for developers to expose data via HTTP service.  WebAPI is extremely easy to configure when compared to WCF services, and can send content in a multitude of formats.  On top of that you can easily extend it at almost any level.  While WebAPI shipped with MVC 4, it can easily be used in Asp.Net AJAX as well!  In this blog we will take a look at setting up WebAPI in ASP.Net Web Forms

Before We Get Started

To follow along with this blog you will need to download and install MVC 4 Beta.  You can get the bits here. Once you run the installer, you are all set to continue on. :)

One Step Setup

The first thing we need to do is create a new project.  For this example I used a standard ASP.NET AJAX project template.

image 

With the project created, it's time to add a few references.  In the solution explorer, right click on the References folder and select Add Reference.

Add the following references:

System.Web.Http.dll
System.Web.Http.Common.dll
System.Web.Http.WebHost.dll

The project is now setup to work with WebAPI. That was much easier than configuring a WCF service, wasn’t it? :)

Now it’s time to get down to business!

WebAPI is based on routes, which are almost identical to MVC routes.  That means we need to configure routes which will be used to access the ApiControllers in our application.

To do this, open the global.asax in your project, and enter the following basic route in the Application_Start method:

RouteTable.Routes.MapHttpRoute( 
                   name: "DefaultApi", 
                   routeTemplate: "api/{controller}/{id}", 
                   defaults: new { id = System.Web.Http.RouteParameter.Optional } );

Note: To keep visual studio from yelling at you, and to make the project compile, you will need to add using statements for: System.Web.Http, and System.Web.Routing.

If you have worked with ASP.NET MVC, this route should look very familiar.  Basically, this route says: when a request comes in that starts with ‘/api’, send it to {controller}, and if there is an id in the url, go ahead and pass it along too. 

With the route set up, we need to add a controller to handle the specified route! 

In the solution explorer right click on the asp.net project, and select Add > New Folder, and name the new folder Api.  Next right click on the new folder, and select Add New Item

In the Add New Item dialog, select Web API controller, give the controller a name, and click Add.

image

Now we need to create an entity to expose through the service.  In this example I created a very simple Customer entity:

 
public class Customer
{
 public int Id { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
}
 

Note: Make sure the object you want to expose has a parameter-less constructor! Otherwise there will be serialization issues.

The last thing we need to do in the controller, is make a new action method to return an IQueryable<Customer> as shown here:

// GET /api/<controller>
public IQueryable<Customer> Get()
{
 return repository.Get();
}

In the Get Customer method I am simply returning a Queryable list of Customers.  When you expose the entity set as IQueryable<T>, WebAPI allows you to query the data set using some of the OData operators.  This can be really helpful for only returning the entities you really need on the client!

Creating the Client

Now that the project is set up, and the service is created, we can set up a web form page to load this data. 

Add jQuery to the page by adding the script tag in the head, or dragging and dropping it onto the page from the solution explorer.

Now create a simple list:

<ul id=”customerList>
 
</ul>
 

And then create the following jQuery function:

$(function () {
      $.ajax({
          url: '<%=Page.ResolveUrl("~/api/customers")%>',
          type: "GET",
          contentType: "application/json;charset=utf-8",
          statusCode: {
              200: function (results) {
 var customerList= '';
 for (var i = 0; i < results.length; i++) {
 var currentResult =results[i];
                      customerList += "<li>" + currentResult.FirstName + " " + currentResult.LastName + "</li>"
                  }
                  $('#customerList').html(customerList);
              }
          }
      });
  });

This function will call the new service method, and create a list item for each customer as shown here:

image

That is not very nice looking, so how about we use a grid instead?  Telerik’s Grid for ASP.NET AJAX already has support for binding to OData, and as I mentioned earlier, when you expose your entities using IQueryable<T> many of the same OData operators can be used.

To get this data to display in RadGrid, copy and paste the following:

<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
 <scripts>
 <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
 <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
 <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
 </scripts>
 </telerik:RadScriptManager>
 <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
 <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
 <telerik:RadGrid ID="RadGrid1" GridLines="None" runat="server" AutoGenerateColumns="true">
 <mastertableview commanditemdisplay="None" horizontalalign="NotSet" >
 <Columns>
 <telerik:GridBoundColumn DataField="FirstName" HeaderText="First Name" 
 UniqueName="FirstName" DataType="System.String" />
 <telerik:GridBoundColumn DataField="LastName" HeaderText="LastName" 
 UniqueName="LastName" DataType="System.String" />
 <telerik:GridBoundColumn DataField="Id" HeaderText="Id" Display="false" 
 UniqueName="Id" DataType="System.Int32" />
 </Columns>
 </mastertableview>
 <ClientSettings>
 <DataBinding Location="http://localhost:36955/api" ResponseType="JSON">
 <DataService TableName="Customers" Type="OData" />
 </DataBinding>
 <Scrolling AllowScroll="True" UseStaticHeaders="True" SaveScrollPosition="True" />
 </ClientSettings>
 </telerik:RadGrid>
 <telerik:RadWindowManager ID="RadWindowManager1" runat="server">
 </telerik:RadWindowManager>
 </telerik:RadAjaxPanel>

Now it should look something like this:

image

Much better!  Now we have data pulling from our new WebAPI controller, and displaying on an ASP.Net Web Form. 

That is where I will end today.  Next time we will take a look at editing this data, and saving it back to the controller, so stay tuned!

Happy Coding!

Download the RadControls trial today!


About the Author

Iana Tsolova

is Product Manager at Telerik’s DevTools division. She joined the company back in the beginning of 2008 as a Support Officer and has since occupied various positions at Telerik, including Senior Support Officer, Team Lead at one of the ASP.NET AJAX teams and Technical Support Director. Iana’s main interests are web development, reading articles related to geography, wild nature and latest renewable energy technologies.

Related Posts

Comments

Comments are disabled in preview mode.