Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: return Redirect and ViewData

Tags:

c#

asp.net-mvc

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

like image 367
pistacchio Avatar asked Jul 05 '09 16:07

pistacchio


2 Answers

You probably want to use the TempData property, this will be persisted across to the next HTTP request.

like image 65
roryf Avatar answered Sep 23 '22 07:09

roryf


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;
      });
  });
like image 27
tvanfosson Avatar answered Sep 19 '22 07:09

tvanfosson