WCF is a very cool framework for adding an abstraction layer over your services.  You can have .asmx, .svc, and now, REST URLs with no extension.  These endpoints can even return JSON to the caller, which is useful if you’re using jQuery or another JavaScript library.

The knock on WCF?  The configuration story!  It’s getting better in WCF 4, which is scheduled for release in a month or so.  It will have a bunch of defaults so you don’t have to be as explicit in your config file.  Finally, some convention over configuration in the WCF space!  Now someone needs to create a fluent, code-based configuration tool for the exceptions to the default conventions…

Don’t be afraid of JSON!

Jason But if you need to return JSON to a caller today, you don’t need scary WCF config files to do it.  You can get the same URL and the same data payload with a lot less hassle using MVC controller actions.

The steps are:

  1. Create a new action in a controller.
  2. Grab your data or whatever you want to return.
  3. Parse your data to JSON.
  4. Throw it back out to the requestor.

The trick is to use JsonResult as the return type for your controller action and convert your output to a JSON string with the base controller’s Json method:

public JsonResult GetAllDepartments()
{
    var departments = _repository.GetAllDepartments();
    return Json(departments);
}

Now if I browse to this controller action (I’m using the HomeController in this example):

http://localhost/Home/GetAllDepartments

I get a pop-up to save the response stream, which I can open with Notepad:

[{"Name":"Human Resources"},{"Name":"Accounting"},{"Name":"IT"},{"Name":"Pencil Sharpening"}]

Yeah, JSON!  And there was no gory config setup needed!

Using jQuery with JSON

Now we can use jQuery in the MVC view to take advantage of this returned JSON. 

Here’s a view that has a button and a div tag.  jQuery is being used to tie the button click to a call to the controller and action we set up above.  It then gets the JSON coming back, loops through it, and puts it in the div tag so it’s visible to the user.

<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    
<script type="text/javascript">
    $(function() {
        $("#btnShowDepartments").click(function() {
            $.getJSON("/Home/GetAllDepartments", null, function(data) {
                for (item in data) {
                    var department = data[item];
                    $("#divDepartments").append(department.Name, ", ");
                }
            });                
        });
    });        
</script>   

<p>
    <input id="btnShowDepartments" type="button" value="Show Departments" />
    <div id="divDepartments"></div>
</p>

This is probably not the best jQuery in the world.  I’m still new to it.  But the point is to show that you can put a URL in, parse the JSON, and use the data however your app needs it.