I want to change the layout of application, in my application there are two type of user Admin and Member, from admin member can login. I want to change the layout to member when login as member from admin.
Here is my code
public ActionResult UserLogin(string email, int type)
{
#region SignOut Admin First
//signout First
if (Session["id"] != null)
{
UserLogBL ul = new UserLogBL();
UserLog lg = ul.GetByID(Convert.ToInt32(Session["id"]));
lg.logout = Convert.ToDateTime(System.DateTime.Now.ToLongTimeString());
ul.Update(lg);
}
Session.Clear();
Session.Abandon();
LmsSession.Abandon();
FormsAuthentication.SignOut();
#endregion
//getting user detail
LearnerBL learnerBL = new LearnerBL();
int id = learnerBL.GetIdBYName(email);
Learner learner = learnerBL.GetByID(id);
if (learner != null)
{
String role = LoginUser(learner);
if (string.Equals(role.ToLower(), "admin"))
return RedirectToAction("Index", "AdminDashboard");
return RedirectToAction("Index", "LearnerMyLearning");
}
return RedirectToAction("Login", "Account");
}
In the respective views you can set the layout that the view should use.
#Layout="~/Views/Shared/LayoutNameHere.cshtml"
Related
I need to display the users info when he selects View Profile. How can I do this as im new to mvc. Links to help or an explanation will help a lot. Thanks
Here is my Login Action:
public ActionResult Authorize(The_Pizzatorium.Models.tblUser userModel)
{
using (The_PizzatoriumEntities1 db = new The_PizzatoriumEntities1())
{
var userDetails = db.tblUsers.Where(x => x.dUSerName == userModel.dUSerName && x.dPassword == userModel.dPassword).FirstOrDefault();
if (userDetails == null)
{
userModel.LoginErrorMessage = "Wrong username or password.";
return View("Index", userModel);
}
else
{
Session["UserID"] = userDetails.dID;
Session["userName"] = userDetails.dUSerName;
return RedirectToAction("Index", "Home");
}
}
}
How will I need to make the View Profile Action to display the logged in Users Details?
public ActionResult ViewProfile()
{
return View();
}
when user come to viewprofile action check use session
public ActionResult ViewProfile()
{
if(Session["UserID"]!=null)
{
//check user uid datatype
//then store in variable
int useesionid=COnvert.toint32(Session["UserID"].tosting())
var userDetails = db.tblUsers.Where(x => x.uid==useesionid).ToList();
///here your code
return View( userDetails );
}
Check the below code, to get the user details if logged in other wise redirecting to login page.
public ActionResult ViewProfile()
{
if(Session["UserID"] != null)
{
using (The_PizzatoriumEntities1 db = new The_PizzatoriumEntities1())
{
int userId = Convert.ToInt32(Session["UserID"].ToString());
var userDetails = db.tblUsers.Where(x => x.dID == userId).FirstOrDefault();
if (userDetails != null)
{
return View(userDetails);
}
}
}
return RedirectToAction("Login", "Account"); // Redirect to your login page
}
I have several roles for users in my website.
I need to return different view on user role.
Now I have call View default way
public ActionResult Index()
{
return View();
}
But I need this: if user has Admin role I return Index.cshtml.
If it has user role I need to return IndexUser.cshtml.
How I can realize it?
UPDATE
I tried to realize it like this
public ActionResult Index()
{
if (User.IsInRole("Admin"))
{
return View();
}
if (User.IsInRole("Test"))
{
return View("IndexProjectManager");
}
return View();
}
But it always going to return View
if you want to do itin view then you can use below to redirect to another view:
return RedirectToAction("Reporting", "ReportManagement", new { area="Admin" })
I mean on the basis of condition as below:
if (isAdmin)
{
return view();//supposing it is the view for admin
}
else
{
return RedirectToAction("Reporting", "ReportManagement", new { area="Admin" })
}
if (User.IsInRole("admin")) //whatever your admin role is called
{
return View();
}
if (User.IsInRole("user"))
{
return View("IndexUser");
}
return View("Whatever"); //or RedirectToAction(...)
Note: I'm basing this on assuming how your Roles work...apologies if this isn't quite appropriate.
You could make it so that Index View is the lowest level (basic) user view then have suffixes appended to each 'higher' role's views.
That way, you could do something like this:
[Authorize] //make sure they're logged in
public ActionResult Index()
{
string _viewSuffix = "";
//this bit would have to be hierarchical - high to low - so you have a degradation of what the view offers...
if (User.IsInRole("Admin"))
{
_viewSuffix = "Admin";
}
else if(User.IsInRole("Test"))
{
_viewSuffix = "Test";
}
//...and so on
return View("Index" + _viewSuffix);
}
//I Have a Action Method
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(VmUser_User VmUser_User)
{
if (VmUser_User.User_User.UserName == null ||
VmUser_User.User_User.Password == null)
{
VmUser_User.LblError = "Please enter Username and Password";
return View(VmUser_User);
}
//Return valid user
if (VmUser_User.LoginUser() > 0)
{
Session["One"] = VmUser_User;
return RedirectToAction("Index", "Home");
}
else
{
VmUser_User.LblError = "User/Password does not match!";
}
return View(VmUser_User);
}
//And another Action Method
public async Task<ActionResult> Common_Unit()
{
Oss.Romo.ViewModels.User.VmUser_User user =
(Oss.Romo.ViewModels.User.VmUser_User)Session["One"];
if (user == null)
{
return RedirectToAction("Login", "Home");
}
vmCommon_Unit = new VmCommon_Unit();
await Task.Run(() => vmCommon_Unit.InitialDataLoad());
return View(vmCommon_Unit);
}
When a valid user login application, it redirect to Home/Index page, then he request for Common/Common_Unit page. After expire the session and user relogin the application I want to redirect in last requested page like Common/Common_Unit, please someone help me to solve this problem.
My Question : When a authorized user browse a specific page then he inactive some time. In the min time session out occurred and user go to login page. After login I want to redirect user on this specific page. Sorry for my Bad English
Try to use ReturnUrl parameter, like this:
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(VmUser_User VmUser_User)
{
if (VmUser_User.User_User.UserName == null ||
VmUser_User.User_User.Password == null)
{
VmUser_User.LblError = "Please enter Username and Password";
return View(VmUser_User);
}
//Return valid user
if (VmUser_User.LoginUser() > 0)
{
Session["One"] = VmUser_User;
if (Request.QueryString["ReturnUrl"] != null & Request.QueryString["ReturnUrl"] != "")
{
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
VmUser_User.LblError = "User/Password does not match!";
}
return View(VmUser_User);
}
//And another Action Method
public async Task<ActionResult> Common_Unit()
{
Oss.Romo.ViewModels.User.VmUser_User user =
(Oss.Romo.ViewModels.User.VmUser_User)Session["One"];
if (user == null)
{
return RedirectToAction("Login", "Home", new { ReturnUrl = "/Common/Common_Unit" });
}
vmCommon_Unit = new VmCommon_Unit();
await Task.Run(() => vmCommon_Unit.InitialDataLoad());
return View(vmCommon_Unit);
}
I'm trying to authorize that if you are an admin, you will be redirected to an admin site. If you are a member, it will redirect you to the member site.
Here is my code on the controller:
public ActionResult Index(Login model)
{
if (ModelState.IsValid)
{
if (model.IsUserExist(model.EmailId, model.Password))
{
if (Roles.IsUserInRole("Admin"))
{
ViewBag.UserName = model.EmailId;
FormsAuthentication.RedirectFromLoginPage(model.EmailId, false);
return RedirectToAction("AdminSite", "Home");
}
if (Roles.IsUserInRole("Member"))
{
ViewBag.UserName = model.EmailId;
FormsAuthentication.RedirectFromLoginPage(model.EmailId, false);
return RedirectToAction("MemberSite", "MobileHome");
}
}
else
{
ModelState.AddModelError("", "Wrong Email or Password!");
}
}
return View(model);
}
I don't know what is wrong, but the site just stays on the login page. It just refreshes when I login as a member or admin. It didn't take me to the admin site or member site.
To use
RedirectFromLoginPage(
string userName,
bool createPersistentCookie
)
method you have to have ReturnURL variable name in the querystring. See the specyfication. So it don't get to return RedirectToAction("MemberSite", "Home") or return RedirectToAction("AdminSite", "Home"). If you will comment out that method it will redirect you to given action.
I created my own login logic for a set of web applications. A future version of this project will have a portal-like interface which would then utilize the ASP.NET MVC login logic.
One thing I am trying to figure out is how to build a return URL dynamically based on what controller/action I am in. I am currently doing:
public ActionResult Action(LogggedInCustomer logIn, string id)
{
if (logIn == null)
return RedirectToAction("Index", "Home",
new { returnUrl = "/AR/Invoice/Print/" + id });
}
The application will reside in a folder on the server (domain.com/app). I want to build the return UL more dynamically (if possible). How would I do this?
By using the Url property:
public ActionResult Action(LogggedInCustomer logIn, string id)
{
if (logIn == null)
{
var returnUrl = Url.Action("Print", "Invoice", new { area = "AR", id = id });
return RedirectToAction("Index", "Home", new { returnUrl = returnUrl });
}
...
}