I m building a MVC 3 applications. The application should be able to display a different layout according to the sub domaine (ex: customer1.mysite.com -> layout1; customer2.mysite.com -> layout2; etc...) it will have also a layout for mobile and IE 6.
I have seen that their is the _ViewStart.cshtml that I can leverage to do the logic to set the layout. But what I don't get is where is the controler for that? Should I write all the code in the view?
An other question with layout how to do you factor out the code for the common behaviours? Do you have a controler for that?
And a last one I have seen the concept of areas in asp.net MVC2 is it obsolete now that we have Razor?
Thank you for your help
Fred
This sounds like a good time to use ViewBag.
The idea is that during OnActionExecuting, you would look up the subdomain and shove it into the ViewBag. This can be done in a custom BaseController from which your other controllers inherit, or from an ActionFilter.
Then, in your _ViewStart, you can write a switch statement on ViewBag to control layout.
For example, here is an ActionFilter that will populate @ViewBag.Subdomain in any of your Razor views, including _ViewStart.cshtml.
public class AddSubdomainToViewDataAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var subdomain = filterContext.HttpContext.Request.Url.Authority.Split('.').First();
var controller = filterContext.Controller as Controller;
controller.ViewData.Add("Subdomain", subdomain);
}
}
Then, decorate your controllers with this new [AddSubdomainToViewData] attribute.
Finally, in _ViewStart.cshtml, do something like this:
@{
Layout = "~/Views/Shared/" + ((@ViewContext.ViewData["Subdomain"] as String) ?? String.Empty) + "_layout.cshtml";
}
This will use a different Razor layout for each subdomain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With