Reputation: 11329
We currently have a site which has a section LatestNews, required:false defined in the layout and all views except two have the section which have the same call RenderPartial("ShowLatestNews")
Is there a better way to do this ? i.e. follow the DRY principle - define it in one place and hide/not use it in those 2 views only ?
UPDATE -
currently the layout is dynamically selected from a dbconfig based on user Ideally we don't want to switch layout based on say controller and action combination
Upvotes: 0
Views: 2300
Reputation: 5492
There are really a ton of different directions this question opens up, a lot of these paths are dictated by the current design.
While others are cut and paste solutions
Lets say currently that you have two pages that are completely different from the master layout for the website, but are similar to each other (ex admin pages) or pages that may have the same layout for other 'forseeable' pages. Then I would recommend to change your layout for these pages - Diversifying each layout for their separate uses:
An Admin Page
@{
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
A Regular Page
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
But now lets say that You/I/Whoever really just want these pages to be apart of the main layout but need them to be a Little different based on some information (ex admin, VIP tabs) Strange the idea changes a little here, do we want the Controller to decide what to do or does the View already have this information... The data could ideally be put in a ViewModel or the ViewBag or Session data - again depends :)
By User - HTTP Context (cut & paste solution...)
<div id="specific-content">
@if (User.Identity.IsAuthenticated && User.IsInRole("admin")) <!--RoleProvider-->
{
<div>My Admin Content!</div>
<!--In your case render something (or not)!-->
@{ Html.RenderPartial(...); }
}
else
{
<div>I'm not special :( </div>
}
</div>
Or instead of putting the above code in the layout or on a page put it directly into a Partial
Theirs also one more that I was thinking of, and that is to redirect to a page if the user is a certain person, which I'm not a big fan of - stick to layouts and the User
in the view.
These are the simpler ideas that I had in mind, hope that helped!
Upvotes: 1
Reputation: 1926
This might now be the most eloquent solution but it's simple. In your layout page use this code for your partial:
@if (ViewBag.HideSection == null)
{
@Html.RenderPartial("ShowLatestNews")
}
Now in the 2 controller actions you DON'T want the partial to render add this:
ViewBag.HideSection = true;
It will only hide the partial in those places you specify something in the ViewBag. It isn't evaluating true or false, just the presence of the property.
Upvotes: 0