Search
Close this search box.

ASP.NET MVC 3 – Creating a Simple Log-In Form

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 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: ASP.NET,ASP.NET MVC

Share This Post:

This article is part of the GWB Archives. Original Author: Vinz`Blog

Related Posts