How to create login page in mvc5 ~ is a programming blog which focused on Web Programming and development

Sunday, 3 September 2017

How to create login page in mvc5

01:19:00 Posted by raviteja swayampu 1 comment
In this post we gonna learn about how to create login page(custom) in mvc5. The scope of this article is,
1.Creating database for login page.
2.How to add ADO.NET entity data model.
3.How to add Controller and Code to validate credentials.
4.How to perform validations on form using jquery.
5.Output of simple login application.
You know is a platform to learn,read and explore contents related to web development.Here,In ASP.NET MVC series i have explained some basic and advanced web applications like Registration page,Realtime form validation using jquery,Registration using jquery,CRUD operations using EF,file upload etc in this site.
Now come current application login page using mvc5.

how to create login page in aspdotnet mvc5

I will explain in step by step manner.

Create database for login page application

1.Create a web application in visual studio using empty mvc template.
2.Right click on App_Data folder --> Add --> New Item --> Sql Server Database --> Name it --> Click Add button.
3.Open server explorer --> right click on database you added --> add new query.
4.A sql query editor will open.Now paste below sql script to create a table name 'TUser' with two sample records and  run the code.
--- Table Schema
CREATE TABLE [dbo].[TUser] (
    [Id]       INT           NOT NULL,
    [Name]     NVARCHAR (50) NOT NULL,
    [Username] NVARCHAR (50) NOT NULL,
    [Password] NVARCHAR (50) NOT NULL,
--- Sample Data
INSERT INTO [dbo].[TUser] ([Id], [Name], [Username], [Password]) VALUES (1, N'Raviteja Swayampu', N'[email protected]', N'FFnWc0JJYfJ9/djoDCZXDw==')
INSERT INTO [dbo].[TUser] ([Id], [Name], [Username], [Password]) VALUES (2, N'Chanakya Mandava', N'', N'FFnWc0JJYfJ9/djoDCZXDw==')

Add ADO.NET Entity DataModel

1.Right click on Models folder --> Add --> ADO.NET Entity DataModel --> Name it --> Select EF designer from Database from Entity Data Model Wizard --> Select connection string and web.config --> click next --> Choose your database objects and settings(here table you created) and give name to model namespace--> click finish.
2.Visual studio will add required model and database context classes to solution like below.

how to create login page in aspdotnet mvc5

Add Controller and Code to Validate Credentials

1.Right click on Controllers folder --> Add --> Controller --> Select MVC5 Controller --> name it.
2.Replace controller code with below code.
public class HomeController : Controller
        public ActionResult Index()
            return View();
        public JsonResult Index(string UserName,string Password)
            TUser user = new TUser();
            string msg = "";
                using (DatabaseEntities db = new DatabaseEntities())
                    user = db.TUsers.Where(x => x.Username.Equals(UserName)).FirstOrDefault();
                    if (user != null)
                        string decryptedpasswd = CommonUtilities.Decrypt(user.Password);
                        if(user.Username==UserName && decryptedpasswd == Password)
                            Session["UserName"] = user.Name;
                            msg = "Mr/Ms '"+user.Name+"' Your Login successful";
                            msg = "Email and Password not matched";
                        user = null;
                        msg = "Login failed:Invalid credentials";
            catch(Exception ex)
                throw ex;
            return Json(msg,JsonRequestBehavior.AllowGet);
3.Here Index method(HttpPost) accepts username and password from Index view and checks whether they exists in database and checks credential matched or not.

Note: In realtime applications passwords are stored in database with encryption.So,we have to decrypt it before comparing.(see how to encrypt and decrypt in mvc using C#).

Add View for Index action & Create design Login screen

1.Right click on Index action --> Add View --> Name it --> Click Add.
    ViewBag.Title = "Index";
@using (Html.BeginForm("Index", "Home"))
<div class="container">
    <div class="card card-container">       
        <img id="profile-img" class="profile-img-card" src="//" />
        <p id="profile-name" class="profile-name-card"></p>
        <form class="form-signin">
            <div class="form-group">
                <input type="text" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
                <span style="color:red;" id="spninputEmail"></span>
            <div class="form-group">
                <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
                <span style="color:red;" id="spninputPassword"></span>
            <div id="remember" class="checkbox">
                    <input type="checkbox" value="remember-me"> Remember me
            <button class="btn btn-lg btn-primary btn-block btn-signin" onclick="Login();" type="button">Sign in</button>
        </form><!-- /form -->
        <a href="#" class="forgot-password">
            Forgot the password?
    </div><!-- /card-container -->
</div><!-- /container -->
2.The login screen look like below.
login screen in aspdotnet mvc5

Add jquery script to validate form & Send data to Controller

3.Add below jquery script to perform validations on  login form.these validations fill fire when we click on Sign In button.
  $(document).ready(function () {
        $('input').focus(function () {
    function Login() {
        var isvalid = Validateform();
        if (isvalid) {
            var url='@Url.Action("Index", "Home")';
            $.post(url, { UserName: $.trim($("#inputEmail").val()), Password: $.trim($("#inputPassword").val()) }, function (data) {
                    alert('Invalid credentials');
    function Validateform() {
        var result = true;
        var emailReg = /^([\w-\.][email protected]@([\w-]+\.)+[\w-]{2,4})?$/i;
        if ($.trim($("#inputEmail").val()) == "") {
            $("#spninputEmail").text("Email Required");
            result = false;
        else if (!emailReg.test($.trim($("#inputEmail").val()))) {
            $("#spninputEmail").text("Enter Valid Email");
            result = false;
        else {
        if ($.trim($("#inputPassword").val()) == "") {
            $("#spninputPassword").text("Password Required");
            result = false;
        else {
        return result;

4.Login() function sends the user entered username and password to controller using jquery ajax post method.
5.Validateform() function validates textboxes present in login form.
6.custom css styles and jquery script code for attractive login screen.
body, html {
    height: 100%;
    background-repeat: no-repeat;
    background-image: linear-gradient(rgb(104, 145, 162), rgb(12, 97, 33));
.card-container.card {
    max-width: 350px;
    padding: 40px 40px;
.btn {
    font-weight: 700;
    height: 36px;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    cursor: default;
.card {
    background-color: #F7F7F7;
    /* just in case there no content*/
    padding: 20px 25px 30px;
    margin: 0 auto 25px;
    margin-top: 50px;
    /* shadows and rounded borders */
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
.profile-img-card {
    width: 96px;
    height: 96px;
    margin: 0 auto 10px;
    display: block;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
    border-radius: 50%;
/* Form styles*/
.profile-name-card {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin: 10px 0 0;
    min-height: 1em;
.reauth-email {
    display: block;
    color: #404040;
    line-height: 2;
    margin-bottom: 10px;
    font-size: 14px;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
.form-signin #inputEmail,
.form-signin #inputPassword {
    direction: ltr;
    height: 44px;
    font-size: 16px;
.form-signin input[type=email],
.form-signin input[type=password],
.form-signin input[type=text],
.form-signin button {
    width: 100%;
    display: block;
    margin-bottom: 10px;
    z-index: 1;
    position: relative;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
.form-signin .form-control:focus {
    border-color: rgb(104, 145, 162);
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgb(104, 145, 162);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgb(104, 145, 162);
.btn.btn-signin {
    /*background-color: #4d90fe; */
    background-color: rgb(104, 145, 162);
    /* background-color: linear-gradient(rgb(104, 145, 162), rgb(12, 97, 33));*/
    padding: 0px;
    font-weight: 700;
    font-size: 14px;
    height: 36px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    border: none;
    -o-transition: all 0.218s;
    -moz-transition: all 0.218s;
    -webkit-transition: all 0.218s;
    transition: all 0.218s;
.btn.btn-signin:focus {
    background-color: rgb(12, 97, 33);
.forgot-password {
    color: rgb(104, 145, 162);
    color: rgb(12, 97, 33);

7.After entering valid credentials in login form the success message comes like below.

login successful message
8.With invalid credential the message comes like below.
login failed invalid credentials
9.With valid email and invalid password..
login page email and password required
10.Download source code for this application Download.


I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

1 comment: