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

Login Form in Asp.Net MVC 4


ASP.NET MVC ASP.NET MVC 
Ratings:
6 Comment(s)
 43645  View(s)
Rate this:

Login Form in Asp.Net MVC 4

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:


 

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

{

    public class Login

    {

        [Required(ErrorMessage = "Username is required")] // make the field required

        [Display(Name = "Username")]  // Set the display name of the field

        public string username { get; set; }

        [Required(ErrorMessage = "Password is required")]

        [Display(Name = "Password")]

        public string password { get; set; }

        public bool 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 = new SqlConnection(connString))

            {

                conn.Open();

                SqlCommand cmd = new SqlCommand("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>

    <add name="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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        [HttpGet]

        public ActionResult Index()

        {

            return View();

        }

        [HttpPost]

        public ViewResult 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:


And add the below code in it:

@model LoginFormApp.Models.Login

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div style="margin:0 auto; 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>

                        <input type="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;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="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:



If you click on the “Submit” button now:



You will see the validation error messages shown as above:

Now write the appropriate values in the textbox like this:



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


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



Nice article

By Pravesh Singh on   2 years ago
Nice article for beginners

Good Article

By Chintoo Semi on   2 years ago
Good Article

helpful article

By Ankit Singh on   2 years ago
helpful article

Login Form in Asp.Net MVC 4

By Md Anwar Hossain on   one year ago
Many many thanks umit Kesarwan. 

Thank you

By Jagadheesh AP on   10 months ago
Thank God & you...Because you saved me...I went through a lot of articles that made me hectic...But this one made me cool

super

By Shaikh Asif on   6 months ago
very nice bro

Don't want to miss updates? Please click the below button!

Follow MindStick