I've written some code to load a section of my application between views. While my code works, I'm wondering if there is a better way to do it. (partial views perhaps?) I currently load the views, then show/hide them depending on a button click.
<div id="wrapper">
@*Sidebar*@
@Html.Partial("_AdministrationSidebar")
@*PAGE CONTENT*@
<div id="page-content-wrapper">
<div id="manage" style="clear: both;"></div>
<div id="edit" style="clear: both;"></div>
<div id="create" style="clear: both;"></div>
</div>@*page-content-wrapper*@
</div>@*wrapper End*@
<script>
$(document).ready(function () {
$("#manage").load("RolesAdmin/Manage/");
});
function editItem(Id) {
$("#edit").load("RolesAdmin/Edit/" + Id);
$("#manage").hide();
$("#edit").show();
}
function createItem(Id) {
$("#create").load("RolesAdmin/Create/" + Id);
$("#manage").hide();
$("#create").show();
}
function manageItem() {
$("#manage").show();
$("#create").hide();
$("#edit").hide();
}
</script>
1 Answer 1
This is a nice simple approach to an SPA. I assume you are returning partial pages from your actions.
A slight improvement would be to hide all pages before showing. This way you don't have to touch the other functions when adding a new page.
Add a class to the page divs, like class='partial-page'. Then in your show page function:
function createItem(Id) {
$(".partial-page").hide();
$("#create").load("RolesAdmin/Create/" + Id);
}
You could also make things more generic and allow for a query string. e.g.
function showPage(url, param){
$(".partial-page").hide();
if ($.isPlainObject(param) {
$("#create").load(url + '?' + $.param(param));
}
else {
$("#create").load(url + '/' + param);
}
}
function createItem(Id) {
showPage("RolesAdmin/Create", id)
}
function showSomeOtherPage(id, name) {
// RolesAdmin/SomeOtherPage?id=123&name=freddy
showPage("RolesAdmin/SomeOtherPage", {id:id, name:name})
}
Further, you can support the back button by using jquery.history.js