Geeks With Blogs

News

Microsoft MVP


Moderator at CodeASP.NET


Quiz Master




free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

This demo is a continuation of my previous article about "ASP.NET MVC 3: Creating a Simple Sign-Up Form" which I wrote few months ago. Basically in this post I'm going to demonstrate how to create a simple LogOn form in which users can supply their username and password. And how to authenticate and validate users in ASP.NET MVC 3.

I will not elaborate more in details about the model, view and controllers function so before you go any further, I'd suggest you to check my previous article first about "ASP.NET MVC 3: Creating a Simple Sign-Up Form" especially if you are new to MVC web development approach.

As a recap, here's the previous project structure below:

mvcpart2a

STEP 1: Creating a Model class

To get started let's go ahead and create a simple model class for our Log-in. To do this just right click on the "ViewModels" folder and then select Add -> then select class. In this example I'm going to name the class as "UserLogon" with the following properties below:

using System.ComponentModel.DataAnnotations;

namespace MVCDemo.Models.ViewModels
{
    public class UserLogon
    {
        [Required]
        [Display(Name = "User Login")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    }
} 

The fields defined above will be used in our Login form. You may also noticed that the fields are decorated with Required, Display and DataType attributes. These attributes are called Data Annotations.

STEP 2: Creating the View

Now right click on the "Account" folder and then select Add -> and then select View. A popup window should appear in which you can configure the view for the page. In this demo I'm going to name the view as "LogOn". Now select Razor (CSHTML) as the view engine then check the “Create a strongly-type view” checkbox. Under the model class drop down, select “UserLogOn” class. Then under scaffold template select Create. Take a look at screen shot below for a reference.

mvcpart2b

Click Add to generate the view and the pre-defined codes for you. Here's the generated markup below with some text modifications:

@model MVCDemo.Models.ViewModels.UserLogon 

@{ 
    ViewBag.Title = "Log On"; 
} 

<h2>LogOn</h2> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
        <legend>User Logon</legend> 

        <div class="editor-label"> 
            @Html.LabelFor(model => model.UserLogIn) 
        </div> 
        <div class="editor-field"> 
            @Html.EditorFor(model => model.UserLogIn) 
            @Html.ValidationMessageFor(model => model.UserLogIn) 
        </div> 

        <div class="editor-label"> 
            @Html.LabelFor(model => model.Password) 
        </div> 
        <div class="editor-field"> 
            @Html.EditorFor(model => model.Password) 
            @Html.ValidationMessageFor(model => model.Password) 
        </div> 

        <p> 
            <input type="submit" value="Log On" /> 
        </p> 
    </fieldset> 
} 

<div> 
    @Html.ActionLink("Return to Home page","Index", "Home") 
</div> 

 

Again as a recap, the mark-up above is a strongly-type view. This enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. In this case it uses the MVCDemo.Models.ViewModels.UserLogon .

STEP 3: Adding the GetuserPassword() method

Under ObjectManager folder, add this method in UserManager class.

public string GetUserPassword(string userLogIn) { 
            var user = from o in dre.SysUsers where o.SysUserLoginID == userLogIn select o; 
            if (user.ToList().Count > 0) 
                return user.First().SysPassword; 
            else 
                return string.Empty; 
} 

 

The method above gets the user password from the database based on the user login provided by the user using LINQ query.

STEP 4: Adding the LogOn ActionResults in the AccountController

Add the following code below in the AccountController under "Controllers" folder.

        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(UserLogon model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserManager userManager = new UserManager();
                string password = userManager.GetUserPassword(model.UserLogIn);

                if (string.IsNullOrEmpty(password))
                {

                    ModelState.AddModelError("", "The user login or password provided is incorrect.");
                }

                if (model.Password == password)
                {
                    FormsAuthentication.SetAuthCookie(model.UserLogIn, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Welcome", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

 

As you can see there are two methods above with the same name. The first "LogOn" method will return the LogOn.cshtml that we have just created in STEP 2. The second LogOn method is decorated with the "[HttpPost]" attribute which indicates that the overload of the "LogOn" method can only be invoked for POST requests.

The second method will be triggered once the Button "Log On" is fired. What it does is first it will check if the required fields are supplied so it checks for ModelState.IsValid condition.It will then create an instance of the UserManager class and call the GetUserPassword() method by passing the userLogIn value supplied by the user to get the password. If the password returns an empty string then it will display an error to the view. If the password supplied is equal to the password retrieved from the database then it will redirect the user the the Welcome page, otherwise display an error stating that the password supplied is invalid.

STEP 5: Implementing Log-Out functionality

The log-out code is pretty easy. Just add the following method below in the AccountController class.

// GET: /Account/LogOff 

public ActionResult LogOff() 
{ 
      FormsAuthentication.SignOut(); 

      return RedirectToAction("Index", "Home"); 
}

 

You can then add the following Logout ActionLink in the “Welcome” view.

@Html.ActionLink("Logout", "LogOff", "Account")

The Output

The Log-in page

mvcpart2c

Screen shot that shows the validation

mvcpart2d

After successful Log-on

mvcpart2e

That's it! I hope someone find this post useful!

Technorati Tags: ,
Posted on Friday, December 30, 2011 6:14 PM | Back to top


Comments on this post: ASP.NET MVC 3 - Creating a Simple Log-In Form

# re: ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
You can replace

FormsAuthentication.SetAuthCookie(model.UserLogIn, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Welcome", "Home");
}

with

FormsAuthentication.RedirectFromLoginPage(model.UserLogIn, false);

and set up Welcome/Home as your default url in the web.config.
Left by Ryan on Dec 30, 2011 11:57 PM

# re: ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
hi,
pls provide "remember me control" in checkbox
Left by sudha s g on Apr 14, 2012 12:03 PM

# re: ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
Hi, This is a very helpful tutorial. i've faced a problem .
if (model.Password == password) this condition is always failed and always gives me The password provided is incorrect. i think my GetUserPassword(model.UserLogIn) function is not working properly... My LogOn action is like that:
if (ModelState.IsValid)
{
UserManager um = new UserManager();
string pass = um.GetUserPassword(model.email_add);

if (model.password==pass)
{
FormsAuthentication.SetAuthCookie(model.email_add, false);
return RedirectToAction("Welcome", "Home");
}
else
{
ModelState.AddModelError("", "The provided password is incorrect.");

}

}

and my GetUserPassword Function like that:
var user = from o in TLE.users where o.email_add == usermail select o;
if (user.ToList().Count > 0)
{
return user.First().password;

}
else
return string.Empty;
}


please help me......
Left by awlad on Apr 28, 2012 1:27 AM

# ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
Hi..
awlad

plz check the password datatype and size in ur sql server and

in my case i used nchar(50) but i am giving as 123 during registration and remaining 47checteres are empty so,
that way i showing error
Left by Pavan on May 13, 2012 5:46 PM

# re: ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
Hi awlad

use the statement like this
" if (model.UserPassword == password.TrimEnd())" in the password check step..

It will surely help...
Left by Pavan on May 13, 2012 5:50 PM

# re: ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
Can sum1 plz help me how shld i create a Change Password code??
Left by Jinal on Oct 25, 2012 5:22 PM

# re: ASP.NET MVC 3 - Creating a Simple Log-In Form
Requesting Gravatar...
can you please say how to display values after entering login name and password correctly ?
Left by ss on Feb 13, 2013 12:39 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net | Join free