Saturday, February 19, 2011

MVC actions, should I create 2 actions for logging in?

Hi,

In asp.net mvc, I want to create a action for login.

So this is how I am doing it:

  1. create a action/view named login that simply displays the view.

  2. create another action, named login2 that will be the page that handles the form post and checks the database if the username/password are correct. If it is, redirect to somepage, if not, redirect back to the login page with the appropriate error message.

Is this the best way to do this?

From stackoverflow
  • You can create two Login actions one for viewing and one for form posting. Then decorate them with AcceptVerbs attribute to describe which method they will accept. See here for an example http://weblogs.asp.net/scottgu/archive/2008/09/02/asp-net-mvc-preview-5-and-form-posting-scenarios.aspx

    Jeff Sheldon : Yep, this is exactly how I do Logins, and a bunch of other things if it makes sense.
  • I agree with Craig; however, if you want to do it some other way you should come up with some naming conventions to differentiate your ActionMethods and stick to them.

    Before preview 5 i used

    login => authenticate create => insert edit => update

    etc.

  • Here's the pattern I use:

        /// <summary>
        /// Displays the Login screen the first time
        /// to anyone who wishes to view it.
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Login()
        {
            return View();
        }
    
        /// <summary>
        /// Handles the form postback
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateAntiForgeryToken]
        public ActionResult Login(string name, 
                                  string password, 
                                  string ReturnUrl)
        {
            // perform authentication here
    
            if (string.IsNullOrEmpty(ReturnUrl))
                return RedirectToAction("Index", "Main");
    
            return Redirect(ReturnUrl);
        }
    

0 comments:

Post a Comment