I want to change MVC theme dynamically based on querystring parameter in the url.
Eg:
Here 1,2,3 are my customer keys and i have several customers who needs different themes in my websites. So, how can i change the layout in my website based on this key.
Awaiting for your reply.
Regards, Mallikharjun.
I think you could set the layout dynamically in your controller action
public ActionResult Search(int customer)
{
string layout = ... // function which get layout name with your customer id
var viewModel = ... // function which get model
return View("Search", layout, viewModel);
}
Edit :
I think if you want a better solution to change the layout in all view you must create an ActionAttributeFilter which will intercept the result and inject the layout in the viewresult
Your filter :
public class LayoutChooserAttribute : ActionFilterAttribute
{
private string _userLayoutSessionKey = "UserLayout";
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var result = filterContext.Result as ViewResult;
// Only if it's a ViewResult
if (result != null)
{
result.MasterName = GetUserLayout(filterContext);
}
}
private string GetUserLayout(ActionExecutedContext filterContext)
{
if (filterContext.HttpContext.Session[_userLayoutSessionKey] == null)
{
// I stock in session to avoid having to start processing every view
filterContext.HttpContext.Session[_userLayoutSessionKey] = ...; // process which search the layout
}
return (string)filterContext.HttpContext.Session[_userLayoutSessionKey];
}
}
Your action become :
[LayoutChooser]
public ActionResult Search(int customer)
{
var viewModel = ... // function which get model
return View("Search", viewModel);
}
If you want that the attribute is present in all actions, in FilterConfig.RegisterGlobalFilters static method you can add your filter :
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
...
filters.Add(new LayoutChooserAttribute());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.