I'm Tom Jaeschke and you may contact me at tomjaeschke@tomjaeschke.com or (512) 419-8788.

Tuesday, April 6, 2010

easy AJAX?

If you haven't tried returning a JsonResult with ASP.NET MVC by way of jQuery you're missing out on what is finally a painless way to undertake AJAX, the only way I've yet done AJAX that hasn't felt like jamming a square peg into a round hole. Instead of feeling dirty after writing what feels like a hack, one may glow with pride after an implementation that feels as natural as posting a form, as though AJAX was actually intended to be part of web development!


Consider this piece of a View:






Details details = ViewData["Details"] as Details;
string errorMessage = ViewData["SubmissionErrors"] as string;
%>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/json/", null, function(data) {
var hasFullAccess = data.isAdmin;
if (hasFullAccess == true) {
var errorMessage = "<%= errorMessage %>";
if (errorMessage == "") {
$('#pageEditing').attr('style', 'display: block;');
if ("<%= details.formDisplayed %>" == "True") {
$('#formPreview').removeClass('noshow');
}
if ("<%= details.formExtraFieldDisplayed %>" == "True") {
$('#extraField').removeClass('noshow');
}
} else {
$('#errorMessage').attr('style', 'display: block;');
}
} else {
window.location.replace("/login/");
}
});




 

I reach out http://www.example.com/json/ in line six above to get a Json object with this in it:


{"isAdmin":true}


...or this in it:


{"isAdmin":false}


...to see if a user really has permissions to be viewing the content at the View.


(see my controller and my schema if it helps)

No comments: