blog

Home / DeveloperSection / Blogs / Login Form in Asp.Net MVC 4

Login Form in Asp.Net MVC 4

Sumit Kesarwani83965 10-Feb-2014

In this blog, I’m explaining how to create a login form in asp.net mvc 4.

Step 1:

Create a Login table in the database and add the values like this:


Login Form in Asp.Net MVC 4 

Now create an empty asp.net mvc 4 application and add a model class named “Login.cs” to the project and write the below code in it:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace LoginFormApp.Models
{
    publicclassLogin
    {
        [Required(ErrorMessage = "Username is required")] // make the field required
        [Display(Name = "Username")]  // Set the display name of the field
        publicstring username { get; set; }
        [Required(ErrorMessage = "Password is required")]
        [Display(Name = "Password")]
        publicstring password { get; set; }
        publicbool checkUser(string username, string password) //This method check the user existence
        {
            bool flag = false;
            string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; // Read the connection string from the web.config file
            using (SqlConnection conn = newSqlConnection(connString))
            {
                conn.Open();
                SqlCommand cmd = newSqlCommand("Select count(*) from Login where username='" + username + "' and password='" + password + "'", conn);
                flag = Convert.ToBoolean(cmd.ExecuteScalar());
                return flag;
            }
        }
    }
}

Step 2:

Now add the connection string in the web.config file like this:

<connectionStrings>
    <addname="ConnectionString"connectionString="Data source = YOUR DATA SOURCE NAME; Initial Catalog=YOUR DATABASE NAME; Integrated security=true;"providerName="System.Data.SqlClient"/>
  </connectionStrings>

Step 3:

Now add a controller and named it “HomeController.cs” and write the below code like this:

using LoginFormApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LoginFormApp.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        [HttpGet]
        publicActionResult Index()
        {
            return View();
        }
        [HttpPost]
        publicViewResult Index(Login login)
        {
            if (ModelState.IsValid) // Check the model state for any validation errors
            {
                if (login.checkUser(login.username, login.password)) // Calls the Login class checkUser() for existence of the user in the database.
                {
                    return View("Show", login); // Return the "Show.cshtml" view if user is valid
                }
                else
                {
                    ViewBag.Message = "Invalid Username or Password";
                    return View(); //return the same view with message "Invalid Username or Password"
                }
            }
            else
            {
                return View(); // Return the same view with validation errors.
            }
        }
    }
}

Step 4:

Now add a view by right clicking on the Index() method (Unparameterized one) and add a view which must be a strongly typed View like this:

Login Form in Asp.Net MVC 4


And add the below code in it:

@model LoginFormApp.Models.Login
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <divstyle="margin:0auto; text-align: center; border: 2px; border-style: solid; width:400px;background-color:bisque">
        @using (Html.BeginForm())
        {
            <table>
                <tr>
                    <td>@Html.LabelFor(m => m.username)</td>@*Label to display username*@
                    <td>@Html.TextBoxFor(m => m.username)</td>@*Textbox for user input*@
                   
<td>@Html.ValidationMessageFor(m => m.username)</td>@*Show validation error (if any) on form submission*@
                </tr>
                <tr>
                    <td>@Html.LabelFor(m => m.password)</td>@*Label for pasword*@
                    <td>@Html.PasswordFor(m => m.password)</td>@*Password box for inputting password*@
                    <td>@Html.ValidationMessageFor(m => m.password)</td>@*Show validation errors(if any) on form submission*@
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <inputtype="submit"value="Submit"/></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        @ViewBag.Message
                    </td>
                </tr>
            </table>
        }
    </div>
</body>
</html>

Step 5:

Now add another view to the project by right clicking on the Index() method (Parameterized one this time) and give the view name “Show.cshtml” like this:

@model LoginFormApp.Models.Login
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>Show</title>
</head>
<body>
    <div>
        <h3> Hi! @Model.username</h3>@*Show the name of th euser who is logged in.*@
    </div>
</body>
</html>

Output

Now run the application:


Login Form in Asp.Net MVC 4

If you click on the “Submit” button now:


Login Form in Asp.Net MVC 4

You will see the validation error messages shown as above:

Now write the appropriate values in the textbox like this:


Login Form in Asp.Net MVC 4

And click on submit button, you will see the message if the user is valid like this:


Login Form in Asp.Net MVC 4

And if write any wrong username or password, you have the message like this:


Login Form in Asp.Net MVC 4


Updated 18-Sep-2014

Leave Comment

Comments

Liked By