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
}
Related
I want to put an admin role privileges in my post method in controller.
Whatever login I use, the takes it as if everyone has an admin role. Any ideas on what needs to change so the code execute correctly in the if statement?
Thank you.
[HttpPost]
public ActionResult Autherize(Vidly2.Models.User userModel)
{
using (LoginDataBaseEntities db = new LoginDataBaseEntities())
{
var userDetails = db.Users.Where(x => x.Email == userModel.Email && x.Password == userModel.Password).FirstOrDefault();
var admins = db.Users.Where(x => x.Role.Contains("Admin")).FirstOrDefault();
if (userDetails == null)
{
userModel.LoginErrorMessage = "Wrong username or password.";
return View("Index", userModel);
}
else {
if (admins == null)
{
return RedirectToAction("Index", "Home");
}
else
{
Session["userID"] = userDetails.Email;
return RedirectToAction("Index", "Keys");
}
}
}
return View();
}
//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 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"
i have an asp.net mvc4 application in which i have in an action X :
impaire_target = u.Get_Impaire_List().Find(x => x.id_paire == identificateur);
Session["id_paire"] = a;
return RedirectToAction("Page2","Pages",impaire_target );
The action Page2
public ActionResult Page2(Impaire impa)
{
try
{
User u = (User)Session["user"];
if (u.Login == null) RedirectToAction("Index", "Home");
}
catch { return RedirectToAction("Index", "Home"); }
if (impa == null)
{
return View();
}
return View(impa);
}
the problem is that the parameters impa is always null . even i try to replace return RedirectToAction("Page2","Pages",impaire_target ); by return RedirectToAction("Page2","Pages",new{ impa=impaire_target} ); i got the same result.
What is the reasons of this problem?
You can't use ModelBinding with RedirectToAction, so no complex type as anonymous object. Try to convert the object to a RouteValueDictionary:
return RedirectToAction("Page2", "Pages", new RouteValueDictionary(impaire_target));
Side note: you always have to return the RedirectToAction, or it won't work.
You should use Session or TempData for passing complex data between controller actions. Here it is described in details.
Example:
impaire_target = u.Get_Impaire_List().Find(x => x.id_paire == identificateur);
TempData["impa"] = impaire_target;
Session["id_paire"] = a;
return RedirectToAction("Page2","Pages");
The action Page2
public ActionResult Page2()
{
Impaire impa = TempData["impa"] as Impaire;
try
{
User u = (User)Session["user"];
if (u.Login == null) RedirectToAction("Index", "Home");
}
catch { return RedirectToAction("Index", "Home"); }
if (impa == null)
{
return View();
}
return View(impa);
}
I have this controller:
[Authorize]
public class CheckoutController : Controller
{
ShoppingCartContext storeDB = new ShoppingCartContext();
const string PromoCode = "FREE";
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
try
{
if (string.Equals(values["PromoCode"], PromoCode,
StringComparison.OrdinalIgnoreCase) == false)
{
return View(order);
}
else
{
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Save Order
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Process the order
var cart = Models.ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
return RedirectToAction("Complete",
new { id = order.OrderId });
}
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
public ActionResult Complete(int id)
{
// Validate customer owns this order
bool isValid = storeDB.Orders.Any(
o => o.OrderId == id &&
o.Username == User.Identity.Name);
if (isValid)
{
return View(id);
}
else
{
return View("Error");
}
}
}
And I have created a View called AddressAndPayment under Checkout, so it goes to localhost/Checkout/AddressAndPayment but I only get a 404 error, even if I right click on the View and click on view in Page Inspector. I don't know why its not even showing the view when it is created.
You need a corresponding HttpGet method, as your current one only accepts a HttpPost request. Add the following:
[HttpGet]
public ActionResult AddressAndPayment()
{
return View();
}