Created
August 21, 2012 09:14
-
-
Save joeriks/3413814 to your computer and use it in GitHub Desktop.
Simple razor api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@functions{ | |
// URL : /macroScripts/api/order/get/{id} [GET] | |
protected override void InitializePage() | |
{ | |
// UrlData[0] is the first url part after the path, in our case the {id} | |
var orderId = UrlData[0].AsInt(); | |
Json.Write(WebApp.Db.SingleOrDefault<Order>(orderId),Response.Output); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@functions{ | |
// URL : /macroScripts/api/order/insert [POST] | |
protected override void InitializePage() | |
{ | |
// Deserialize input stream to Order object | |
var jsonData = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd(); | |
var order = Json.Decode<Order>(jsonData); | |
Json.Write(Convert.ToInt32(WebApp.Db.Insert(order)), Response.Output); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// using Knockout ViewModels | |
// Save | |
viewModel.save = function (form) { | |
my.utils.postJs("/order/insert", ko.toJSON(viewModel), function (newOrderId) { | |
viewModel.orderId(newOrderId); | |
}); | |
} | |
... | |
// Get | |
my.utils.getJs("/order/get/" + orderId, function (data) { | |
var viewModel = ko.mapping.fromJS(data); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Helper to make the get / post syntax a little bit cleaner | |
var my = my || {}; | |
my.utils = { | |
postJs: function (url, data, callback) { | |
url = "/macroScripts/api" + url; | |
$.ajax({ | |
url: url, | |
data: data, | |
type: 'POST', | |
dataType: 'json', | |
contentType: 'application/json; charset=utf-8', | |
success: callback | |
}); | |
}, | |
getJs: function (url, callback) { | |
url = "/macroScripts/api" + url; | |
$.ajax({ | |
url: url, | |
dataType: 'json', | |
contentType: 'application/json; charset=utf-8', | |
success: callback | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment