Skip to content

WebAPI with SPA (Single Page JavaScript) Specifically ExtJS and Sencha Touch

Updated: at 02:12 PM

I’ve really gotten to like using Microsoft’s ASP.NET WebAPI with JavaScript.  No longer do I have to worry about the JSON conversion and error status.  With a very simple pattern of what to return, it just works.

In this post, I’m just going to show the code for the controller itself.  Not any kind of camelcase filters, error handling, security, or anything else.  Just the simple controller.  All those other things can be handled without touching the code I’m showing here.

Basically, all we have to do is create an HttpResponseMessage and return that.  The code I have below is actually production in Silicon Valley Code Camp and just returns a list of all the session levels.  It’s pretty self explanatory.

public class SessionLevelController : ApiController
{
/// <summary>
/// if passed in with sessionId then set true or false along with tag. always get all tags
/// </summary>
/// <returns></returns>
public HttpResponseMessage Get()
{
var sessionLevels =
SessionLevelsManager.I.GetAll();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK,
new
{
data = sessionLevels,
total = sessionLevels.Count,
success = true
});
return response;
}
}

What the data looks like to the JavaScript is as follows:

{
"data": [
{
"description": "Beginner",
"id": 1
},
{
"description": "Intermediate",
"id": 2
},
{
"description": "Advanced",
"id": 3
}
],
"total": 3,
"success": true
}

And, if you are curious, in ExtJS, the store definition and model definition follow.

Ext.define('SS.model.SessionLevelModel', {
extend: 'Ext.data.Model',

fields: [
{
name: 'description'
},
{
name: 'id'
}
],
proxy: {
type: 'ajax',
url: '/rest/SessionLevel',
reader: {
type: 'json',
root: 'data'
}
}
});

Ext.define('SS.store.SessionLevelStore', {
extend: 'Ext.data.Store',

//sorters: [{
// property: 'description',
// direction: 'ASC' // or 'ASC'
//}],

requires: [
'SS.model.SessionLevelModel'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
model: 'SS.model.SessionLevelModel',
}, cfg)]);
}
});

That’s it! very simple.

HTH’s.

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects