简体   繁体   中英

asp.net mvc 2 - return JavaScript with View

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 (ie, 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

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"] %>
public JavaScriptResult Index() 
{
    return JavaScript("<script type='text/javascript' language='javascript'> $(document).ready(function () { console.log('hi hi hi'); }); </script>"); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM