How to dynamically set style in a list item in _Layout.cshtml
asp.net-mvc-3, jquery, razor
Solution
If you add a click event handler to the group of `a` elements, you can easily add the class to the clicked element's `li` and remove it for all siblings, regardless of how many there are. This removes the need for the if statements and the `attr` update for each `li`.
Here's a sample:
http://jsfiddle.net/JjBgm/4/
markup:
<ul id="menu">
<li><a href="#">one</a></li>
<li><a href="#">two</a></li>
<li><a href="#">three</a></li>
</ul>
jQuery:
$(document).ready(function() {
$('#menu li a').click(function() {
$(this).parent().addClass('selected').siblings().removeClass('selected');
});
});
You'd have to obviously modify this approach to your needs with MVC, but the concept should work.
EDIT: Because you mentioned there is a round-trip to the server involved the above may not work well. In that case you could construct the clientside id based on the selected menu and control the class from there.
$(document).ready(function () {
var selMenu = '@ViewBag.SelectedMenu';
$("#" + selMenu).addClass('selected').siblings().removeClass('selected');
});
This is assuming `#page1`, `#page2`, etc. refer to the `<li>` elements without seeing your resulting markup after server processing.
If `#page1` refers to the `<a>` tag, then your statement would be:
$("#" + selMenu).parent().addClass('selected').siblings().removeClass('selected');
Untested of course. Main point is dynamically construct your selector, then use sibling and parent selectors as needed to clear the class. It's much cleaner.
Problem
I have this menu in _Layout.cshtml : ``` <td class="MenuStructure"> <ul id="menu"> <li>@Html.ActionLink("First Page", "Page1Action", "Main")</li> <li>@Html.ActionLink("Second Page", "Page2Action", "Main")</li> <li>@Html.ActionLink("Third Page", "Page3Action", "Second")</li> </ul> </td> ``` When one of the action links is clicked, I want to set the class of the <li> which contains it to "selected" and the class of the other <li> elements to "". This works : ``` <script type="text/javascript"> $(document).ready(function () { var selMenu = '@ViewBag.SelectedMenu'; if (selMenu == "page1") { $("#page1").attr('class', 'selected'); $("#page2").attr('class', ''); $("#page3").attr('class', ''); } if (selMenu == "page2") { $("#page1").attr('class', ''); $("#page2").attr('class', 'selected'); $("#page3").attr('class', ''); } }); </script> ``` but it is awfully ugly. Can someone show me a more elegant way to do this?