Practical .NET

Posting Data to ASP.NET Sites with the ASP.NET Web API

Peter returns to the ASP.NET Web API in Visual Studio 2012 to use it with ASP.NET. And this time, he's moving complete objects from the client up to the server in an HTTP POST.

I've looked at the new ASP.NET Web API before, but only at retrieving data and only in the ASP.NET MVC template generated by Visual Studio 2010. In this column, I want to do two other things: use the ASP.NET Web API in a conventional ASP.NET Web application, and using it to post back whole objects to the server.

This scenario also lets me mention one of the features of the latest release of the ASP.NET Web API. I'm still using Visual Studio 2010 and .NET 4.5, so this is another instance of the "IMpractical .NET" column -- but this is exciting technology (see this column for a good description of why the ASP.NET Web API is so cool for Ajax-enabling applications).

Setting up the Application
The first step in using the API with ASP.NET is to add, from the Add New Item menu, an ASP.NET API Controller class to your project (you must put the controller in the project's App_Code folder). To support the conventions of the routing process (see the next paragraph), the class name must end in Controller (I called my class "CustomersController").

Since the controller you've just added is a code file, you can't request it directly in a URL. Your next step, then, is to add routing to your Global.ASAX file in its Application_Start method that converts a valid URL into a request for this controller class. You'll need to use the MapHttpRoute method, and to get that method you'll need to add a namespace declaration for System.Web.Http to the top of your controller class:

using System.Web.Http;
The simplest route you can specify consists of a name for the routing and a template that converts all requests (except requests for pages) into the name of a controller. That routing looks like this:

RouteTable.Routes.MapHttpRoute("CustomerAPI", "{controller}" );

At this point, assuming my Web site's URL is http://localost:1867/, I'll be able to call the default get method in my controller (at least, the get method without parameters) by entering the URL http://localost:1867/customer into my browser's address bar. If you do a similar test with Internet Explorer, you should get a message that you have a 19 byte file available for download.

Coding the Client
The jQuery code that I want to use on the client to post data back to the server uses the ajax method from the jQuery 1.6 library. So, first, I need to pick up that library:

<script type="text/javascript" src="Scripts/jquery-1.6.2.js" ></script>
I also need to add a button to start the data transfer:

<input type="button" id="SendData" value="Send Data"/>
And I need to attach to the button's onclick event the function that will post data to the client:

<script type="text/javascript">
$("SendData").click(SendCustomerData);

In real life, I'd pull the data from the page to create the object that's going back to the server. For this example, I'll just hard-code a Customer object:

var customer = {CustomerID: "A123",
                CustomerName: "PHVIS"};
I'm now ready to write the function that uses jQuery's ajax function to send the data to the server. I need to specify the URL (the name of my controller), that I'm using HTTP POST, and that the content is a JSON object. I also need to convert my customer object to a JSON object:

function SendCustomer()
{  
 $.ajax({url:"customer",
         type: "POST",
         contentType: "application/json;charset=utf-8",
         data: JSON.stringify(customer)});
}
</script>
Coding the Server
Back at the server, I need to define the Customer object I want to load my JSON data into when it arrives from the client:

public class Customer
{
   public string CustomerID {get; set; }
   public string CustomerName {get; set; }
}

The Web API base controller includes a method called Post that will automatically execute when the controller receives an HTTP POST request. However, in the latest version of the Web API, that default code in the Post method won't actually work -- the method's parameters will always be null.

An HTTP POST sends the data up in the body of the request; and in the latest version of the Web API, you have to tie the Post method's parameter to the request's body. You do that by decorating the method's parameter with the FromBody attribute. And, as with any parameter, you have to specify the data type of the parameter. In my case, my Customers controller's Post method that accepts a Customer object looks like this:

public void Post([FromBody] Customer Cust)
{
  if (cust.CustomerID == "A123")
  {
	//code to work with the Customer object
  }            
}

And that's all there is to it: One class on the server and a jQuery call on the client. There's more I could do (send a response back to the client about what happened on the server, for instance), but this little bit of code does what I want: Posts an object from my browser to the server for processing.

About the Author

Peter Vogel is a system architect and principal in PH&V Information Services. PH&V provides full-stack consulting from UX design through object modeling to database design. Peter tweets about his VSM columns with the hashtag #vogelarticles. His blog posts on user experience design can be found at http://blog.learningtree.com/tag/ui/.

comments powered by Disqus

Featured

  • Full Stack Hands-On Development with .NET

    In the fast-paced realm of modern software development, proficiency across a full stack of technologies is not just beneficial, it's essential. Microsoft has an entire stack of open source development components in its .NET platform (formerly known as .NET Core) that can be used to build an end-to-end set of applications.

  • .NET-Centric Uno Platform Debuts 'Single Project' for 9 Targets

    "We've reduced the complexity of project files and eliminated the need for explicit NuGet package references, separate project libraries, or 'shared' projects."

  • Creating Reactive Applications in .NET

    In modern applications, data is being retrieved in asynchronous, real-time streams, as traditional pull requests where the clients asks for data from the server are becoming a thing of the past.

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

Subscribe on YouTube