Reputation: 677
I am beginning to use ASP.NET MVC and i have a navigation which is build with javascript and css. The Navigation is collapsable, so that the menu only takes like 1cm when its collapsed. My problem is that i need to change the state (collapsed/expanded) by clicking on a button and setting a css class on the menu. But when i click on a menu-entry the page gets reloaded and so the css-class gets lost too.
How can i persist such data correctly? In normal views i could pass it to my viewmodel, but how can i do this in my _layout.cshtml? (i cant set a model there, right?)
What i tried was using the jquery plugin "cookies" but it only works sometimes (i think the problem is somewhere within the options of the plugin - maybe i have to set a domain or something...). Furthermore it would be nice if the solution wouldnt require the user to allow cookies.
Im glad for any help!
edit: ok, what i tried now is:
//the view
@model NHibernateSimpleDemoMVC.Models.MenuModel
....
<a id="togglemenu" />
@Html.HiddenFor(x => x.IsCollapsed, new { @id = "collapsedHdn" })
...
<script>
jQuery('#togglemenu').click(
function () {
if (jQuery("#collapsedHdn").val() == "true") {
jQuery("#collapsedHdn").val("false")
} else {
jQuery("#collapsedHdn").val("true")
}
});
jQuery('#nav > li').click(
function () {
var name = jQuery(this).attr("id");
jQuery("#selectedHdn").val(name);
}
);
jQuery(document).ready(function () {
//set selected node
if (jQuery("#collapsedHdn").val() == "true") {
... collapse ...
}
if (jQuery("#selectedHdn").val() != "") { //this is always empty ("")
var name = "#" + jQuery("#selectedHdn").val();
jQuery(name).addClass("current");
}
});
</script>
//the model
public class MenuModel
{
public bool IsCollapsed { get; set; }
public string SelectedEntry { get; set; }
public MenuModel(){
IsCollapsed = false;
SelectedEntry = "";
}
}
... my hidden fields seem to not keep their value after the postback...
Upvotes: 0
Views: 694
Reputation: 1629
There's a useful related question: ASP.NET MVC Razor pass model to layout
Upvotes: 1
Reputation: 2932
There's usually a correlation between a value on the page and the navigation menu item pointing to that page. E.g a Title or something like that.
If there is, then you can use jQuery/Javascript to set the css class once the DOM is fully loaded by reading this value and finding the corresponding menu item.
This is definitely not something you would use cookies for.
Upvotes: 0