Visual Studio 2010 with MVC2 and jQuery Post Callback Issue
Friday, May 07 2010 - mvc
I’ve been doing some prototyping with VS2010 and MVC2 and ran into a problem where the call to $.post(…) wasn’t triggering the callback function. I attached the debugger and verified that my controller was being called and in fact the code appeared to be returning the correct view. Next I fired up Fiddler and verified that in fact the correct view was returning and it rendered the correct HTML.
For my test I was using a PartialView. The out of the box call redirects to a new URL, but I needed to remain on the page and I needed to return only the LoginSuccessResults as a partialview.
I took the default web site login page and altered it to use jQuery.Post() method rather than the out of the box server post-back.
Here’s what my call looked like:
<script type="text/javascript">
$(document).ready(function () {
$('input#submit').click(function () {
var jsonData = new Object();
jsonData.userName = $('#UserName').val();
jsonData.password = $('#Password').val();
$.post('LogOn', jsonData, function (data) { alert('here'); }, 'json');
});
});
</script>
Everything worked great except the callback never fired. The thing that made it odd is that when I first started the callback was firing as expected. I finally had to sit back and ask myself what changed? The answer was simple. The fourth parameter to $.post is ‘json’. Originally I was returning some json formatted data, but later I changed it to use a custom partial view since that handled the rendering in a cleaner fashion. I removed the parameter, so my call is now:
$.post('LogOn', jsonData, function (data) { alert('here'); });
and the callback correctly gets invoked. I must say I am going to seriously regret having to go back to webforms for maintenance.



