views:

261

answers:

1

Hi, using ASP.NET MVC 2 I have a navigation menu inside my Master Page. In the navigation menu, I am trying add a class to the that the current page relates to (i.e., home page will add class="active" to the Home button). I'm trying to consider scalability and the fact that I don't want to change individual pages if the navigation changes later.

The only way I can think of doing this is:

  1. Add JavaScript to each individual View that will add the class when the DOM is ready
  2. Return JavaScript when return View() occurs

on point (2), I am unsure how to do. Thusfar I have been doing the following in my controller:

    public ActionResult Index()
    {
        ViewData["messege"] = JavaScript("<script type='text/javascript' language='javascript'> $(document).ready(function () { console.log('hi hi hi'); }); </script>");

        return View();
    }

but in my view, when I call:

<%: ViewData["messege"] %>

I get: System.Web.Mvc.JavaScriptResult as the result

Would you guys have any ideas on

  • How to solve the navigation menu probelem, other than the solutions I've listed
  • return JavaScript along with your view from the Controller

Thanks, in advanced!

+1  A: 

To fix your code, save a string in the ViewData["message"] variable:

public ActionResult Index()
{
    ViewData["message"] = "<script type='text/javascript' language='javascript'> $(document).ready(function () { console.log('hi hi hi'); }); </script>";

    return View();
}

and then render it on the page with <%= %> and not <%: %>:

<%= ViewData["message"] %>
Shay Friedman
strange. I could have SWORN I tried that. I know that using <%: %> will basically say HTML.Encode()... but than what does the <%= %> do?
Tomaszewski
also, would you have an idea to on how to solve the navigation menu probelem, other than the solutions I've listed?
Tomaszewski
<%: %> does Html.Encode and <%= %> doesn't. For navigation menus I generally recommend using ASP.NET's navigation capabilities with sitemaps and all. Read more about it. I think the next page will be a good start: http://www.asp.net/mvc/tutorials/providing-website-navigation-with-sitemaps-cs
Shay Friedman
sitemaps. Interesting, will read. Thanks much!
Tomaszewski