I am working on a Partial view that is controlled by a Switch case statement in my controller function for Login and Register but after logging in successfully, it only refreshes the page and doesnt redirect on the case that is used on the login controller function , My problem is how can I prevent to go in the return View(model)
Here is my Main Controller
[HttpPost]
public ActionResult Dashboard(RegisterModel model1, LogOnModel model2, string returnUrl, string btnReturn, string Role, FormCollection formCollection)
{
switch (btnReturn)
{
case "Register":
DashboardRegister(model1, Role, formCollection);
break;
case "Login":
DashboardLogin(model2, returnUrl);
break;
}
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList());
DashboardRegisterLogin model = new DashboardRegisterLogin
{
RegisterModel = model1,
LogOnModel = model2
};
// If we got this far, something failed, redisplay form
return View(model);
}
Controller Function for Register:
public ActionResult DashboardRegister(RegisterModel model1, string Role, FormCollection formCollection)
{
String name = formCollection["txtClientName"];
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model1.UserName = model1.Email, model1.Password, model1.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model1.UserName, Role);
FormsAuthentication.SetAuthCookie(model1.UserName, false /* createPersistentCookie */);
if (Roles.IsUserInRole(model1.UserName, "Employer"))
{
return RedirectToAction("ClientCustomerDetails", "Customer");
}
else if (Roles.IsUserInRole(model1.UserName, "Worker"))
{
return RedirectToAction("WorkerInfo", "Worker");
}
else if (Roles.IsUserInRole(model1.UserName, "Administrator"))
{
return RedirectToAction("ClientDetails", "Client");
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
// If we got this far, something failed, redisplay form
return View(model1);
}
Controller Function for Login:
[HttpPost]
public ActionResult DashboardLogin(LogOnModel model2, string returnUrl)
{
if (Membership.ValidateUser(model2.UserName, model2.Password))
{
FormsAuthentication.SetAuthCookie(model2.UserName, model2.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
if (Roles.IsUserInRole(model2.UserName, "Employer"))
{
return RedirectToAction("WorkerIndex", "Worker");
}
else if (Roles.IsUserInRole(model2.UserName, "Worker"))
{
return RedirectToAction("PositionIndex", "Position");
}
else if (Roles.IsUserInRole(model2.UserName, "Administrator"))
{
return RedirectToAction("ClientDetails", "Client");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model2);
}
You need to return here as you're not using the results of those methods:
switch (btnReturn)
{
case "Register":
return DashboardRegister(model1, Role, formCollection);
case "Login":
return DashboardLogin(model2, returnUrl);
}
Related
//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);
}
My program was working before. I do not know what changes did I make, but now suddenly my login behaves so weird. Every time I try to access Admin authorized page, it keeps redirecting me to login page, even after I login. Here is my code:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(AlvinCMSExtension.Models.LoginModel model, string returnUrl)
{
string redirectUrl = returnUrl;
string userName = model.UserName;
AlvinCMSExtension.Models.UserProfile user = dbAccount.UserProfiles.Where(m => m.Email.Equals(userName, StringComparison.CurrentCultureIgnoreCase)).SingleOrDefault();
if (user != null)
{
userName = user.UserName;
}
if (ModelState.IsValid && WebSecurity.Login(userName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToAction("LoginRedirectionControl", new { redirectUrl = redirectUrl });
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
public ActionResult LoginRedirectionControl(string redirectUrl)
{
string returnUrl = redirectUrl;
if (redirectUrl == null)
{
redirectUrl = User.IsInRole("Admin") ? "/Admin" : "/";
}
return RedirectToLocal(redirectUrl);
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Home", "Page");
}
And I tried to access this:
[Authorize(Roles="Admin")]
public ActionResult Dashboard()
{
return View();
}
After each successful login, the Redirect(returnUrl) does not take me to the returnUrl, but instead to login page again. The parameter used is: http://localhost:5847/Account/Login?ReturnUrl=%2fAdmin%2fDashboard. I debug the code and the returnUrl is holding /Admin/Dashboard/. I do not know what is happening.
Check if the user has the role "Admin", it may be removed
I have a custom Authorize attribute to handle LogIn. And I need to redirect user to last page after login. For example :
Product Controller
[CustomAuthorize]
public ActionResult Detail(int productID)
{
//code here
return View(model);
}
Let's say user isn't logged in when he tried to access Product/Detail/msi-gtx-970, my web application will redirect the user to LogIn page. I want to redirect user back to Product/Detail/msi-gtx-970 after successful LogIn. How to do that?
My LogIn Controller
[AllowAnonymous]
public ActionResult LogIn()
{
//code here
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult LogIn(string returnUrl)
{
//code here
if (string.IsNullOrEmpty(returnUrl))
{
return View("Index", "Home");
}
return Redirect(returnUrl);
}
Thanks
You need to receive the returnUrl on your get Action;
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
Change your form on the "Login "view passing the url as parameter for posting the url value:
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
....
}
the rest of your code is fine
in your customeAuthorizer attribute you should have the filterContext object and then you can use the following code sample.
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
filterContext.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Please Provide authToken";
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Authentication",
action = "Login",
errorMessage = "Invalid Resourse Access Attempt",
ReturnUrl = filterContext.HttpContext.Request.Path.Value
}));
or you can use the following function for this purpose as well.
public void AuthFailed(AuthorizationFilterContext filterContext)
{
Console.WriteLine(filterContext.HttpContext.Request.Path.Value);
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
filterContext.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Please Provide authToken";
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Authentication",
action = "Login",
errorMessage = "Invalid Resourse Access Attempt",
ReturnUrl = filterContext.HttpContext.Request.Path.Value
}));
}
and in your login (GET) action you can handle it like this.
TempData["ReturnUrl"] = Request.Query["returnUrl"].ToString();
and after the successfull login (when the user successfully logged in) you gotta redirect it to the same requested page. Login (POST)
if (TempData["ReturnUrl"] != null)
{
string[] temp = TempData["ReturnUrl"].ToString().Split('/');
if (temp.Length == 3)
{
return RedirectToAction(temp[1], temp[0], new { id = temp[2] });
}
else if (temp.Length == 1)
{
return RedirectToAction("Index", "Home");
}
else
{
return RedirectToAction(temp[1], temp[0]);
}
}
else
{
return RedirectToAction("Index", "Home");
}
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();
}
I am learning a newly created default simple MVC4 web project.
In the index page, I have a link for the user to log on the site with his account. After that he will be redirected to a form to enter new name, new password.
I have this form ready for validation using [Required]. But as sooon as the redirected page is completely loaded, these controls (username and password) were done validated (Field needs be filled in) too.
Here is the code of POST after the user log in with his account
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToCreateUser(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
and here is the method RedirectToCreateUser
private ActionResult RedirectToCreateUser(string url)
{
if (Url.IsLocalUrl(url))
{
return Redirect(url);
}
else
{
return RedirectToAction("CreateNewUser", "Account");
}
}
finally the CreateNewUser method which is for http GET
public ActionResult CreateNewUser(CreateNewUserModel model)
{
return View(model);
}
and another one for http POST which I think hasn't been accessed yet though.
[HttpPost]
public ActionResult CreateNewUser(CreateNewUserModel model, string url)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, null, true);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("CreateUserSuccess", "Account");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
else
{
}
return View(model);
}
your problem is here
finally the CreateNewUser method which is for http GET
public ActionResult CreateNewUser(CreateNewUserModel model)
{
return View(model);
}
You cannot pass an object as a parameter on a get request. Probably that signature should be
public ActionResult CreateNewUser()
{
var model = new CreateNewUserModel();
return View(model);
}
or something similar
The CreateNewUser action is firing on the [HttpPost] and attempting to post with invalid (empty) credentials.
You need to add something to this effect using [HttpGet]:
[HttpGet]
public ActionResult CreateNewUser(CreateNewUserModel model)
{
return View(model);
}