[英]How to change theme in ASP.Net MVC 5 based on querystring value?
我想根据网址中的querystring参数动态更改MVC主题。
例如:
这里的1,2,3是我的客户密钥,我有几个需要在我的网站中使用不同主题的客户。 因此,如何根据此键更改网站的布局。
等待您的回复。
问候,Mallikharjun。
我认为您可以在控制器动作中动态设置布局
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);
}
编辑:
我认为,如果您想要更好的解决方案来更改所有视图中的布局,则必须创建一个ActionAttributeFilter,它将拦截结果并将布局注入到viewresult中
您的过滤器:
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];
}
}
您的动作变为:
[LayoutChooser]
public ActionResult Search(int customer)
{
var viewModel = ... // function which get model
return View("Search", viewModel);
}
如果希望该属性出现在所有操作中,则可以在FilterConfig.RegisterGlobalFilters静态方法中添加过滤器:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
...
filters.Add(new LayoutChooserAttribute());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.