I have a login box in my MasterPage. Whenever the login information is not correct, I valorize ViewData["loginError"]
to show the error message to the user.
Login is an action of the UserController, so the form that contains the login has action = "/User/Login"
.
As a user can try to log in from any page, in case of success I redirect him to his personal page, but in case of error I want him to stay on the very same page where he tried to login. I've found that this works:
return Redirect(Request.UrlReferrer.ToString());
but it seems that, as I'm not returning a proper view, the data on ViewData is lost, so I cannot show the error message.
Any suggestion on how to solve this and similar problems?
Thanks
You probably want to use the TempData
property, this will be persisted across to the next HTTP request.
Why not handle the login via AJAX instead a full post? You could easily supply the status, a redirect URL, and any error messages via JSON.
public ActionResult Logon( string username, string password )
{
...
// Handle master page login
if (Request.IsAjaxRequest())
{
if (success)
{
return Json( new { Status = true, Url = Url.Action( "Index", "Home" ) } );
}
else
{
return Json( new { Status = false, Message = ... } );
}
}
else // handle login page logon or no javascript
{
if (success)
{
return RedirectToAction( "Index", "Home" );
}
else
{
ViewData["error"] = ...
return View("Logon");
}
}
}
Client-side
$(function() {
$('#loginForm input[type=submit]').click( function() {
$('#loginError').html('');
$.ajax({
url: '<%= Url.Action("Logon","Account") %>',
dataType: 'json',
type: 'post',
data: function() { return $('#loginForm').serialize(); },
success: function(data,status) {
if (data.Status) {
location.href = data.Url;
}
else {
$('#loginError').html( data.Message );
}
}
});
return false;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With