Skip to content

ParallelCodes

  • AngularJS
  • Android
    • Android-Creating Notepad
    • Android Widgets Tutorial
    • Android Send SMS Programmatically with Permissions
    • Making Phone Calls in Android
    • Android JSON Parsing
    • Upload Files from Android to PC Programmatically
    • Android Interview Ques & Ans
  • ASP.NET
  • MVC
  • Xamarin
  • C#
  • WPF
  • CSS Templates

ParallelCodes

  • AngularJS
  • Android
    • Android-Creating Notepad
    • Android Widgets Tutorial
    • Android Send SMS Programmatically with Permissions
    • Making Phone Calls in Android
    • Android JSON Parsing
    • Upload Files from Android to PC Programmatically
    • Android Interview Ques & Ans
  • ASP.NET
  • MVC
  • Xamarin
  • C#
  • WPF
  • CSS Templates

Creating MVC Login Page with SQL Database and Razor

  • by ASH
  • April 15, 2018August 7, 2019
MVC Login Page with SQL Database 04
Post Views: 6,991

Let’s create a simple MVC Login Page with SQL Database and simple MVC Validations. The application will have two basic textboxes required for getting userid and password from the user and a MVC Input Button for calling the Login method.

DOWNLOAD SOURCE CODE FOR THIS APP.

My MS SQL Database Table for UserInfo :

Usertbl –

MVC Login Page with SQL Database 01

Now let’s create our Login Page.

Step 1 : Create a new ASP.NET MVC Project with Razor View Engine. I’m using MVC 4 for this Project.

Step 2 : Create a new Model class name User.cs in Model folder of your MVC Project and edit it as below.

Model > User.cs :

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace MvcApplication1.Models
{
public class User
{

[Required(ErrorMessage = "Please enter your User ID.")]
[Display(Name = "Username : ")]
public string UserId { get; set; }

[DataType(DataType.Password)]
[Required(ErrorMessage = "Please enter your Password.")]
[Display(Name = "Password : ")]
public string Password { get; set; }

public string UserName { get; set; }

//This method validates the Login credentials
public String LoginProcess(String strUsername, String strPassword)
{
String message = "";
//my connection string
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("Select * from Usertbl where UserId=@Username", con);
cmd.Parameters.AddWithValue("@Username", strUsername);
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
Boolean login = (strPassword.Equals(reader["Password"].ToString(), StringComparison.InvariantCulture)) ? true : false;
if (login)
{
message = "1";
UserName = reader["UserName"].ToString();

}
else
message = "Invalid Credentials";
}
else
message = "Invalid Credentials";

reader.Close();
reader.Dispose();
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
message = ex.Message.ToString() + "Error.";

}
return message;
}

}
}

This class declares all the necessary String (get; set;) variables and a method named LoginProcess which accepts two parameters named : UserId and Password with return value of String variable. The returning String will change as per the Login process result which is parsed in the Controller method.

Step 3 : Create a new Controller named UserLoginController.cs in your Controllers folder.  (Note : Please type the name only as UserLogin as Visual Studio will append Controller automatically).

Controllers > UserLoginController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class UserLoginController : Controller
{
//
// GET: /UserLogin/

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

[HttpGet]
public ActionResult UserLogin()
{
return View();
}

//This the Login method. It passes a object of my Model Class named "User".
[HttpPost]
public ActionResult UserLogin(User users)
{
if (ModelState.IsValid)
{
//message will collect the String value from the model method.
String message = users.LoginProcess(users.UserId, users.Password);
//RedirectToAction("actionName/ViewName_ActionResultMethodName", "ControllerName");
if (message.Equals("1"))
{
//this will add cookies for the username.
Response.Cookies.Add(new HttpCookie("Users1", users.UserName));
//This is a different Controller for the User Homepage. Redirecting after successful process.
return RedirectToAction("Home", "UserHome");
}
else
ViewBag.ErrorMessage = message;
}
return View(users);
}

}
}

If the login process is successful, it will redirect it the Homepage of the User.

Now add a View to our Controller method for displaying the login page :

MVC Login Page with SQL Database 02

Right Click on the UserLogin method and Click add View option and name the View as UserLogin.

And Edit it as below.

View > UserLogin > UserLogin.cshtml:

 
@model MvcApplication1.Models.User
@{
ViewBag.Title = "UserLogin";
Layout = "~/Views/Layout/_webLayout.cshtml";
}

<h2>UserLogin</h2>

@using (Html.BeginForm())
{
<table width="100%">
<tr>
<td align="center">
<table class="table-condensed">
<tr>
<td align="left">
@Html.LabelFor(m => m.UserId)
</td>
<td align="right">
@Html.TextBoxFor(m => m.UserId)
&nbsp;&nbsp;
<br />
@Html.ValidationMessageFor(m => m.UserId)
</td>
</tr>

<tr>
<td align="left">
@Html.LabelFor(m => m.Password)
</td>
<td align="right">
@Html.EditorFor(m => m.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "Password" } })
&nbsp;&nbsp;
<br />
@Html.ValidationMessageFor(m => m.Password)
</td>
</tr>

<tr>
<td colspan="2" align="center">
<input type="submit" value="Login" class="btn btn-primary" />
</td>
</tr>
</table>
<br />
<br />
@ViewBag.ErrorMessage;
</td>
</tr>
</table>
}

Step 4 : Creating the User HomePage.

Now Add a new Controller with name UserHomeController.cs and edit it as following :

Controllers > UserHomeController.cs :

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
public class UserHomeController : Controller
{
//
// GET: /UserHome/

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

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

}
}

And create its View with name Home.cshtml. And edit it as below :

Views > UserHome > Home.cshtml :

 
@model MvcApplication1.Models.User
@{
ViewBag.Title = "UserHome";
Layout = "~/Views/Layout/_webLayout.cshtml";
}

<h2>My Homepage</h2>

@*//This will display the username from the cookies to the user.*@
<b><span style="color:blue;font-size:20px;">Welcome @Request.Cookies["Users1"].Value.ToString()</span></b>

Step 5 : Create a MasterPage for our MVC Login Application.

Create a new Folder named “Layout” in the Views folder and create a new layout html page in it. And Edit it as below:

Views > Layout > _webLayout.cshtml:

 
@{
Layout = null;
}
<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>My MVC Application</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body style="font-family: Arial; width: 100%; height: 100%;">
<div style="background-color: #0094ff; color: #fff; font-weight: bold; padding: 25px 5px; font-size: 30px; font-style: italic">
MY MVC WEB APPLICATION
</div>
<br />
<div style="width:100%;text-align:center;">

@RenderBody()
</div>
</body>
</html>

Inside the Content folder of your application solution, copy the bootstrap.css as below (You can download using this Link) :

MVC Login Page with SQL Database 03

DOWNLOAD SOURCE CODE FOR THIS APP.

Output :

MVC Login Page with SQL Database 04

ASP.NET MVC Cookie Add and Retrieve Example with source code download

Also see:

How to upload files in ASP.NET MVC and save in Database.

Binding Angular JS Bind HTML table from SQL in ASP.NET MVC C#

Bind|Populate ASP.NET MVC C# Dropdownlist from SQL

C# ASP.NET MVC Add and Retrieve Cookies

Creating a Login Page in ASP.NET MVC C# using SQL table and Razor

Creating a Registration page in ASP.NET C#


Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Skype (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to print (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to email a link to a friend (Opens in new window)

Related

Tags:asp.net mvcmvc loginmvc login applicationmvc login application with databasemvc login application with sql databasemvc login page

Get all the latest updates for free on Facebook

Get all the latest updates for free on Facebook
 

ASP.NET, MVC
  • Create Login API using .NET Core | ASP.NET C#
  • jQuery – Get Selected Radio Button value
  • ASP.NET C# – Create PDF Invoice using iText7 Library
  • ASP.NET – Creating and Downloading PDF Files
  • ASP.NET MVC Upload Multiple Files using HttpPostedFileBase
  • ASP.NET Upload Multiple Files using FileUpload
  • ASP.NET MVC JQuery AJAX Call to Controller HttpGet and HttpPost
  • ASP.NET MVC Show Notifications using JQuery
  • ASP.NET MVC Razor Display HTML String from Model
  • ASP.NET – Create and Write Text to File
  • ASP.NET MVC – Convert Model to JSON in Javascript
  • ASP.NET – Insert data using SQL Stored Procedures
  • Create ASP.NET Login page with SQL Database
  • Android Create Bottom Navigation bar
  • ASP.NET Gridview Paging Example
  • ASP.NET MVC – How to use JQuery Datatable on Webforms
  • ASP.NET MVC – Using JQuery Datepicker
  • ASP.NET MVC – How to Use REST API Webservice
  • ASP.NET MVC – How to Create REST API Webservice
  • Xamarin Forms – How to use WebView
  • ASP.NET – Use SQL Stored Procedure on WebForms
  • Create and Consume REST API webservices in ASP.NET MVC
  • ASP.NET MVC – Send Mails using Office365 Email SMTPClient
  • MVC – How to Upload and Download Files in ASP.NET MVC Tutorial
  • ASP.NET How to Upload and Download Files with SQL Database

Neve | Powered by WordPress