How to access the Page from ViewUserControl rendered using RenderPartial?

Last post 09-18-2008 1:58 AM by tgmdbm. 1 replies.

Sort Posts:

  • How to access the Page from ViewUserControl rendered using RenderPartial?

    09-17-2008, 5:58 AM
    • Member
      44 point Member
    • dkl
    • Member since 05-16-2003, 5:03 AM
    • Hradec Králové
    • Posts 25

    Suppose you have some page-level logic, like registering javascript blocks. You want to register all the javascripts with the Page and then render them all at the bottom of the page. Is it possible to access Page from ViewUserControl that is rendered using Html.RenderPartial?

    Koupil jsem si francovku, dal jsem za ni 30 korun.
  • Re: How to access the Page from ViewUserControl rendered using RenderPartial?

    09-18-2008, 1:58 AM
    Answer
    • Contributor
      4,372 point Contributor
    • tgmdbm
    • Member since 12-17-2007, 9:08 AM
    • Posts 883
    • ASPInsiders
      TrustedFriends-MVPs

    dkl:
    Is it possible to access Page from ViewUserControl that is rendered using Html.RenderPartial?

    No, they are completely separate.

    One way to do it is to use HttpContext.Items

    public static void RegisterScript( this HtmlHelper helper, string scriptUrl ) {
      var items = helper.ViewContext.HttpContext.Items;
      if( items.ContainsKey("scripts") )
        (items["scripts"] as List<string>).Add( scriptUrl );
      else
        items.Add( "scripts", new List<string>{ scriptUrl } );
    }

    public static string OutputScripts( this HtmlHelper helper ) {
      var items = helper.ViewContext.HttpContext.Items;
      if( !items.ContainsKey("scripts") )
        return string.Empty;
      var scripts = items["scripts"] as List<string>;
      // generate and return <script> tags
    }

     

    So you can call Html.RegisterScript( "~/Content/scripts/abc.js" ) from anywhere, in any view, as long as it's part of the same request.

    I would use something other than "scripts" tho, to avoid naming collisions.

Page 1 of 1 (2 items)