Try our conversational search powered by Generative AI!

How can i get a reference to the current page within a simple view or layout?

Vote:
 
How can i get a reference to the current page within a simple view or layout? I tried "PageReference.SelfReference" but it just gives an exception Content with id - was not found

#172802
Dec 12, 2016 20:37
Vote:
 

Best is to pass it or the properties you need from your controller to the view.

public ActionResult Index(PageData currentPage)
{
    // code here
}

You can also access it directly (bad pattern):

var contentRouteHelper = ServiceLocator.Current.GetInstance<IContentRouteHelper>();

contentRouteHelper.Content as PageData


Hope this helps.

Frederik

#172804
Dec 12, 2016 21:04
Vote:
 

Thank you - although i am trying to get this in a view without a controller. Why is your second solution a bad pattern?

#172805
Dec 12, 2016 21:37
Vote:
 

More logic in view. Logic should be contained in controller or even better in the service layer below controller. More logic in view => harder to read presentation and more difficult to maintain solution if logic is scattered around solution. Single responsibility principle, MVC pattern etc...

#172828
Dec 13, 2016 9:35
Vote:
 

Hi Daniel,

The problem is that there is one block that requires some javascripts placed below the jquery and other scripts. I cannot put these scripts on every page because they are very heavy and will slow every page on the site, rather than just the page that has the javascript application on. I need some sort of switch within the layout that determines whether the current page is the one that needs the extra javascript. The page in question has a reference on the start page properties - so i am currently comparing in the head of the layout. Can you think of an alternative to this? Should i create a second layout and a custom page type that uses just this layout? Would this be a better solution?

Regards,
Marshall

#173174
Dec 15, 2016 18:14
Vote:
 

Use a LayoutModel like in Alloy sample site, or an action method with the ChildActionAttribute.

Frederik

#173181
Dec 15, 2016 18:16
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.