Reputation: 68
I'm having an MVC layout pages which looks roughly like this
<!DOCTYPE HTML
<html class="prod">
<head>
</head>
<body>
</body>
</html>
I want to render the value of class attribute (prod) dynamically based on something returned from my controller.
So far, I tried variations on the following without success
Controller
[ChildActionOnly]
[AllowAnonymous]
public PartialViewResult Environment()
{
return PartialView("Environment", "prod");
}
View
@model string
@Model
Layout
<html class="@{ Html.RenderAction("Environment", "Site"); }">
This actually generates the following
<htmlprod class=""></htmlprod>
<html>
</html>
The same thing happens when I use a ContentResult. To be clear, I do not want to use a Viewbag.
I want to generate a raw HTML string and display that using a PartialView or something similar. The actual value is retrieved through a parameter in the constructor of the controller (ioc).
Upvotes: 0
Views: 1595
Reputation: 54628
You vague question seems to have some deficiencies. Controllers shouldn't be in charge of what environment the application is executing in. I would probably do:
Global.asax:
public class MvcApplication : System.Web.HttpApplication
{
private const string Environment = "Environment";
protected void Application_Start()
{
this.Application.SetEnvironment(Configuration.AppSettings[Environment]);
}
}
HttpApplicationStateExtensions.cs
internal static HttpApplicationStateExtensions
{
private const string Environment = "Environment";
public static void SetEnvironment(this HttpApplicationState state,
string environment)
{
state.Application[Environment] = environment;
}
public static string GetEnvironment(this HttpApplicationState state)
{
var result = state.Application[Environment];
return result;
}
}
WebViewPageExtensions.cs
internal static WebViewPageExtensions
{
private const string Environment = "Environment";
public static string GetEnvironment(this WebViewPage page)
{
var result = page.AppState[Environment];
return result;
}
}
Usage:
<html class="@GetEnvironemnt()">
</html>
Upvotes: 0
Reputation: 218732
You do not need a partial to return you the class name. You may set the class name to the dynamic ViewBag
dictionary and use that in your layout.
public ActionResult Index()
{
ViewBag.HtmlClass="prod";
return View();
}
And in your Layout
<html class="@ViewBag.HtmlClass">
</html>
If you do not wish to use ViewBag, You can create a child action method which simply returns a string.
[ChildActionOnly]
public string Environment()
{
return "production";
}
And in your layout,
<html class="@Html.Action("Environment","Home")">
</html>
Upvotes: 1