Reputation: 30063
I have an ASP.NET MVC web application, all the pages in which use a single master Layout.cshtml
page. Although I usually want to RenderBody()
, I have a site shutdown mechanism that can be enabled in my database so I basically want to have a layout page that looks something like:
@if(DbHelper.SiteIsShutDown) {
<h1>Site is shut down temporarily</h1>
}
else {
<h1>Welcome to the site</h1>
@RenderBody()
}
The trouble is that if SiteIsShutDown
is true, then RenderBody()
doesn't get called and I get the exception:
The "RenderBody" method has not been called for layout page...
So is there a way I can get round this? I just want to render some output from my layout page, and nothing from my view page.
Upvotes: 6
Views: 6820
Reputation: 418
This is the simplest version controlled by cshtml. Advantage of this is you can prevent live hacking attempts by updating cshtml file (which is allowed without restarting the server) if you know the IPs or Session IDs. Simply place the IP in the condition. First block will be viewed as blank if condition is true.
@if (condition)
{
RenderBody();
}
else
{
@RenderBody()
}
Upvotes: 0
Reputation: 3688
Note that you actually can "ignore" the content if you really want to. Normally you write @RenderBody()
in your view code, which evaluates the body content, sticks it in a HelperResult
, and then writes that to the output stream. In doing so, MVC marks the body as having been rendered. You can trick it into thinking the body has been rendered without actually writing anything by writing @{ RenderBody(); }
(notice the braces) or just RenderBody();
if already in a code context. This evaluates the body content without actually writing it to the output stream.
Upvotes: 4
Reputation: 30063
In the end I decided to go with something pretty similar to Jerad Rose's solution, but modified so it just serves up a static file at the root called SiteDisabled.htm
, and also modified so that it doesn't go into an infinite redirect loop when the site is disabled:
protected void Application_BeginRequest(object sender, EventArgs ea) {
string siteDisabledFilePath = "/SiteDisabled.htm";
if (CachingAndUtils.IsSiteDisabled && HttpContext.Current.Request.FilePath != siteDisabledFilePath) {
HttpContext.Current.Response.Redirect(siteDisabledFilePath);
}
}
Upvotes: -4
Reputation: 15513
You probably should leave the master layout to rendering views, and not short-circuit your views in the event of a site shutdown.
You're best bet is to check for this and handle it in Global.asax, i.e. in BeginRequest
:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if(DbHelper.SiteIsShutDown)
{
HttpContext.Current.Response.Redirect("SiteDown");
}
}
Upvotes: 6