问题
In my Web-project (ASP.NET) I need 2 different master pages. One for users like "Admin", and one for the usual users. Where can I indicate what master page to load? How can I load the correct master page, depending on the user?
回答1:
When your admin user try to log in check the username and password with the database and if the login credentials are valid, Set a session variable to indicate this is an admin session. Then you can have a method which returns true of false by checking the session value to tell you whether the current user is an admin or normal user.
When admin login is successfull, set this session variable
Session["adminUserName"]=txtUserName.Text;
Then write a method to check whether the current user is an admin or not
public bool IsAdmin()
{
if(Session["adminUserName"]!=null)
{
return true;
}
else
{
return false;
}
}
Have this method in a common place (like your base class or so ) and check during the page life cycle and load the appropriate master page.
void BasePage_PreInit(object sender, EventArgs e)
{
if(IsAdmin())
{
MasterPageFile = "~/MasterAdmin.master";
}
else
{
MasterPageFile = "~/MasterNormal.master";
}
}
If Its an ASP.NET MVC application, You can check this in your ActionMethod.
public ActionResult Index()
{
if(IsAdmin())
{
return View("Index", "MasterAdmin");
}
else
{
return View("Index", "MasterNormal");
}
}
回答2:
Handle the Page_PreInit
event in code-behind and set the MasterPageFile
property to your liking.
来源:https://stackoverflow.com/questions/8632166/load-different-master-pages-for-different-users