Fun with MVC 4 Web API

Tags: Knockout, pubsub, observer, MVC, jQuery, Ajax, EF, Validation, FluentValidation, Visual Studio 2010, ASP.NET, JSON, FullCalendar, Silverlight, Architecture, Vista, IIS, Generics, NHibernate, WCF, RIA Services, Visual Studio 2008, SQL, STORM!, Nullable, ChannelFactory, netTCPBinding, VSPAT, responsive, design, HTML5, CSS3, MVC WebAPI, MVC 4, WebAPI, JQuery Mobile, ScheduleWidget, recurring events, Ninject, Pluggable, CQRS DDD, Windows

To check out the new Web API templates bundled up in Visual Studio 11, download and install VS 11 Beta.

In this walkthrough I'm using VS 11 Express for Web. Create a new ASP.NET MVC 4 Web Application and choose the Web API project template. Notice the new ApiController class from which ValuesController derives. Let's take it for a test drive. There are two action methods that implement the GET verb:

// GET /api/values
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

// GET /api/values/5
public string Get(int id)
{
    return "value";
}

Go under Views/Home and edit Index.cshtml. After the last DIV tag add the following script:

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON("api/values", function (data) {
            $.each(data, function (key, val) {
                // useless but dramatic jQuery animation
                $('.round').append('<li class=' + key + '>' + val + '</li>');
                $('.' + key + '').text(val).animate({ fontSize: '+=5em' }, 1200);
                $('.' + key + '').text(val).animate({ fontSize: '-=5em' }, 1200);
            });
        });
});
</script>

This is just a simple JQuery ajax call to exercise the out-of-the-box ValuesController. Run it and see the cheap animation. But hey at least it wasn't a blink tag. To pass in an ID to the other GET method the above javascript could be modified to call url api/values/1 instead. How about posting? Modify the POST method to this so that we get back a warm fuzzy response:

// POST /api/values
public HttpResponseMessage<string> Post(string value)
{
    value = string.Concat(value, " processed!"); //using System.Net;
    return new HttpResponseMessage<string>(value, HttpStatusCode.Created);
}

Change the javascript to post a very exciting "value3" string to the controller:

<script type="text/javascript">
    $(document).ready(function () {
        $.post("/api/values", { value: "value3" }, function (data) {
            $('.one h5').text(data);
        });
    });
</script>

Run the app and you should see the response written to the first bullet list item.