Moving MVC2 Helpers to MVC3 razor view engine

Posted by Dai Bok on Stack Overflow See other posts from Stack Overflow or by Dai Bok
Published on 2011-02-11T14:43:52Z Indexed on 2011/02/11 15:25 UTC
Read the original article Hit count: 296

Hi, In my MVC 2 site, I have an html helper, that I use to add javascripts for my pages. In my master page I have the main javascripts I want to include, and then in the aspx pages, I include page specific javascripts.

So for example, my Site.Master has something like this:

....
<head>
    <%=html.renderScripts() %> 
</head>
...
//core scripts for main page
<%html.AddScript("/scripts/jquery.js") %>
<%html.AddScript("/scripts/myLib.js") %>
....

Then in the child aspx page, I may also want to include other scripts.

...
//the page specific script I want to use
<% html.AddScript("/scripts/register.aspx.js") %>
...

So when the full page gets rendered the javascript files are all collected and rendered in the head by sitemaster placeholder function RenderScripts. This works fine.

Now with MVC 3 and razor view engine, they layout pages behave differently, because now my page level javascripts are not rendered/included. Now all I see the LayoutMaster contents.

How do I get the solution wo workwith MVC 3 and the razor view engine. (The helper has already been re-written to return a HTMLString ;-))

For reference: my MasterLayout looks like this:

  ...
  ...
  <head>
  @{
      Html.AddJavaScript("/Scripts/jQuery.js");
      Html.AddJavaScript("/Scripts/myLib.js");
   }
   //Render scripts
   @html.RenderScripts()
  </head>
 ....

and the child page looks like this:

@{
    Layout = "~/Views/Shared/MasterLayout.cshtml";
    ViewBag.Title = "Child Page";
    Html.AddJavaScript("/Scripts/register.aspx.js");
 }
 ....
 <div>some html </div>

Thanks for your help.

Edit = Just to explain, if this question is not clear enough.

When producing a "page" I collect all the javascript files the designers want to use, by using the html.addJavascript("filename.js") and store these in a dictionary - (1) stops people adding duplicate js files - then finally when the page is ready to render, I write out all the javascript files neatly in the header. (2) - this helper helps keep JS in one place, and prevents designers from adding javascript files all over the place. This used to work fine with Master/SiteMaster Pages in mvc 2. but how can I achieve this with razor?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc-3