0

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. Thus far I have been doing the following in my controller:

    public ActionResult Index()
    {
        ViewData["message"] = 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["message"] %>

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

Would you guys have any ideas on

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

2 Answers 2

1

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"] %>
Sign up to request clarification or add additional context in comments.

3 Comments

strange. I could have SWORN I tried that. I know that using <%: %> will basically say HTML.Encode()... but than what does the <%= %> do?
also, would you have an idea to on how to solve the navigation menu probelem, other than the solutions I've listed?
<%: %> 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: asp.net/mvc/tutorials/…
0
public JavaScriptResult Index() 
{
    return JavaScript("<script type='text/javascript' language='javascript'> $(document).ready(function () { console.log('hi hi hi'); }); </script>"); 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.