I am utilizing jQuery UI Tabs in an ASP.NET MVC 2 web application. One part of the application requires that I do error checking when I switch away from the tab. I am doing that via this script within the aspx file that contains the tabs.
<script type="text/javascript">
$(function () {
$("#tabs").tabs({
cache: true,
select: function (event, ui) {
var $tabs = $('#tabs').tabs();
switch ($tabs.tabs('option', 'selected')) {
case 0:
$.post("User/Personal", $("#PersonalForm").serialize(), function (data, success) {
if (success) {
$("#PersonalForm").html(data);
}
});
break;
case 1:
$.post("User/Account", $("#AccountForm").serialize(), function (data, success) {
if (success) {
$("#AccountForm").html(data);
}
});
break;
default:
break;
}
return true;
},
ajaxOptions: {
error: function (xhr, status, index, anchor) {
$(anchor.hash).html("Couldn't load this tab. We will fix this as soon as possible.");
}
}
});
});
</script>
There are additional switch statements (removed for brevity). Basically, this code allows the MVC validation to occur on the tabs via data annotations - works very nicely. In any case, I was wondering if it is possible to have this code "generated" based on whatever tabs I have within my document. (If it isn't, I basically have to code ever case statement within the switch statement by hand, which seems kind of a waste.)
Also, as a side note, I am using ASP controls for each tab to hold the various data (which is also where the individual forms reside). That may make a difference to the solution.
This code, when the user leaves a tab, goes through each form on the tab you're leaving and sends an ajax request as in your code. The difference is that it figures out where to send it based on the form's
action
attribute instead of having to specify this in the switch statement. This meansPersonalForm
's action attribute has to beUser/Personal
and so on.Of course, if you have no more than one form on the page you can skip the
each
and if there are only certain forms that should be submitted this way, you can add a class to them to filter the selection