Introduction
This article explains the following
- How to create an ASP.NET MVC Project
- How to Add ADO.NET Entity Data Model
- How to Add a Controller
- How to validate User Credentials
- How to keep User Details in Sessions and display them in the User Dashboard
1. Design your Database
Create the UserProfile table using the following script.
CREATE TABLE UserProfile
(
UserId INT PRIMARY KEY IDENTITY(1, 1),
UserName VARCHAR(50),
Password VARCHAR(50),
IsActive BIT
);
Insert user records using the following script.
INSERT INTO UserProfile (UserName, Password, IsActive)
VALUES ('jaipal', 'jai1234', 1),
('praveen', 'praveen1234', 1),
('pruthvi', 'pruthvi1234', 1);
2. Create Project
Go to File, New, then click on Project.

Select Visual C#, Web under Installed templates. After that, select ASP.NET MVC 4 Web Application, then mention the Application Name (MvcLoginAppDemo) and Solution Name as you wish, then click OK.

Under Project template, select a template as Basic, then view the engine as Razor. Click OK.

3. Add Entity Data Model
Go to Solution Explorer, right-click on Project, Add, then select ADO.NET Entity Data Model.

Give it a meaningful model name, and then click on Add.

Select Generate from the database and then click on Next.

Click on New Connection.

After clicking on New Connection, we have to provide the following Connection Properties in the following wizard.
- Provide the Server name.
- Select the "Use SQL Server Authentication" radio button.
- Enter the Username and Password in the password text box.
- Check the "Save my password" checkbox.
- Select the "Select or enter a database name:" radio button.
- Select the database to which you want to set the connection.
- Click on the "Test Connection" button to ensure the connection can be established.
- Then click OK.

Select the radio button, and yes, include the sensitive data in the connection string.

Choose your database objects, as in the following image.

Click on Finish. At this point UserProfie entity will be created.

4. Add a Controller
Go to Solution Explorer, right-click on the Controller folder, Add, and then click on Controller.
( Or ) Simply use shortcut key Ctrl + M, Ctrl + C,

Provide the Controller Name and Scaffolding template as Empty MVC Controller. Then click on Add.

Write the following code in HomeController.
using System.Linq;
using System.Web.Mvc;
namespace MvcLoginAppDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserProfile objUser)
{
if (ModelState.IsValid)
{
using (DB_Entities db = new DB_Entities())
{
var obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserId.ToString();
Session["UserName"] = obj.UserName.ToString();
return RedirectToAction("UserDashBoard");
}
}
}
return View(objUser);
}
public ActionResult UserDashBoard()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}
}
}
5. Create Views
Create View for Login Action Method
Right-click on the Login Action method, then click on Add View, as in the following picture.

Create a Strongly Typed View
- View Name must be an action method name.
- Select the view engine as Razor.
- Select Create a strongly typed view CheckBox.
- Select Model class as UserProfile (MvcLoginAppDemo)
- Select the Scaffold template as Empty
- Click on Add

Write the following code in Login.cshtml (view).
@model MvcLoginAppDemo.UserProfile
@{
ViewBag.Title = "Login";
}
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
<fieldset>
<legend>Mvc Simple Login Application Demo</legend>
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@if (ViewBag.Message != null)
{
<p style="border: 1px solid red">
@ViewBag.Message
</p>
}
<table>
<tr>
<td>@Html.LabelFor(a => a.UserName)</td>
<td>@Html.TextBoxFor(a => a.UserName)</td>
<td>@Html.ValidationMessageFor(a => a.UserName)</td>
</tr>
<tr>
<td>@Html.LabelFor(a => a.Password)</td>
<td>@Html.PasswordFor(a => a.Password)</td>
<td>@Html.ValidationMessageFor(a => a.Password)</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login" /></td>
<td></td>
</tr>
</table>
</fieldset>
}
Create View for UserDashBoard Action method same as login view. And write the following code in UserDashBoard.cshtml (View).
@{
ViewBag.Title = "UserDashboard";
}
<fieldset>
<legend>User Dashboard</legend>
@if (Session["UserName"] != null)
{
<text>Welcome @Session["UserName"].ToString()</text>
}
</fieldset>
6. Set as StartUp Page
Go to Solution Explorer, Project, App_Start, then RouteConfig.cs, and change the action name from Index to Login (Login. cshtml as start-up page).

7. Run the Application

Provide the user credentials and click on OK. If you provide valid user credentials, then the user name will be displayed on your dashboard.

Read my articles on SSRS: http://www.c-sharpcorner.com/UploadFile/44fb93/ssrs-tutorial-part-5-embedded-datasets/
I hope you enjoyed it.

Dharmendra Kumar PanditPosted Aug 21, 2022, 5:20 PM
Thank you........
BrendzPosted Jun 23, 2021, 1:02 PM
Hello Jaipal. Thank you for the article. All ran well except the Welcome message after the login is displayed like this. < fieldset > < legend > User DashBoard < /legend> Welcome Brends < /fieldset>. Any advice Code is below @model LoginExample_MVC4.UserMaster @{ ViewBag.Title = "UserDashBoard"; } < fieldset > < legend > User DashBoard < /legend> @if(Session["UserName"] != null) { <text > Welcome @Session["UserName"].ToString() </text> } < /fieldset>
Samar EmadPosted Jan 24, 2021, 7:17 AM
When i run the project i get this error (CS0103: The name 'FromMethod' does not exist in the current context Source Error: Line 5: } Line 6: Line 7: @using (Html.BeginForm("Login", "Home", FromMethod.post)) Line 8: { Line 9: <fieldset>
Azdev XxiPosted Nov 4, 2019, 8:01 PM
Thank the article your
kiran saiPosted Oct 12, 2019, 2:02 PM
Thank you it is working
Waheed RafiqPosted May 27, 2019, 2:22 PM
You made a mistake here you have to [HttpGet] first for your Login
Sai MahantiPosted Feb 20, 2019, 4:40 AM
Thank you.
Ajay koliPosted Nov 27, 2018, 4:59 AM
Thanks for the steps.It is quite easy to understand.However i wanted to know that will this code work if i use it in a real time application?For example when i host my application on a remote web server.I have come across a problem where the last user who has logged in replaces the previous user login(the user who logged in before)
Tushar MahajanPosted Nov 16, 2018, 8:21 AM
With your method code is not working. There are so many errors in your code.
Siva KumarPosted Oct 26, 2018, 6:17 AM
Hi, can you tell me what does ViewBag.Message do here?
R O D OPosted Sep 23, 2018, 5:24 PM
Good job Jaipal Reddy, you are genius
palak shethPosted Sep 13, 2018, 1:01 AM
Superb..thank u
Jhon HernándezPosted Jun 20, 2018, 8:33 PM
The specified schema is not valid. Errors: \ r \ nThe assignment of the CLR type to the EDM type is ambiguous because several CLR types match the EDM type 'UserProfile'. Type CLR previously found 'MvcLoginAppDemo.Models.UserProfile', type CLR just found 'MvcLoginAppDemo.UserProfile'. "}
Nithish ReddyPosted Mar 7, 2018, 11:22 AM
Can you give a sample screen shots
Nithish ReddyPosted Mar 7, 2018, 11:21 AM
Not working in vs 2017 ?
Nithish ReddyPosted Mar 7, 2018, 10:56 AM
In Vs 2017 , Severity Code Description Project File Line Suppression StateError CS0246 The type or namespace name 'UserProfile' could not be found (are you missing a using directive or an assembly reference?)
Ramendra kumar vermaPosted Feb 23, 2018, 5:26 AM
Can you provide this article without entity model
ojabo emmanuelPosted Feb 15, 2018, 6:38 AM
What if i don't want the login user to go the same page
ojabo emmanuelPosted Feb 15, 2018, 6:37 AM
What if i don't the login user to go the same page
ojabo emmanuelPosted Feb 15, 2018, 6:27 AM
How can i send an email to users after successfully login sir.
ketan chavanPosted Jan 27, 2018, 8:17 AM
Hello Jaipal, can you please extend this tutorial in one more step ahead. Like destroy session when i click logout button.
Ahxan XhaniPosted Jan 14, 2018, 7:17 PM
Can we edit user profile or view user details using session?if yes then glad to how my email is [email protected] so much thanks !!jaipal
rajib saifulPosted Jan 14, 2018, 4:38 AM
Hi Jaipal, in my solution exploerr, there is no App_Start folder. Can you please guide me how I can include RouteConfig.cs as per mentioned in your article. BR-Saiful
Sandeeep LambaPosted Jan 8, 2018, 12:29 PM
Hi jaipal sir, i am new to mvc. May i kniw more abt dis..i wanna ur personal contact email so that i can catch u directly if u dont mind plz
Jai Prakash SaraswatPosted Nov 18, 2017, 2:49 PM
Hlo jaypal. Very nice example, i m searching for this one. thanks.
jigar ModiPosted Nov 17, 2017, 2:19 AM
Nice article Jaipal.... But can you help me with Code First Approach by coding it manually....Instead of using DB Entities !!
Asad NaeemPosted Nov 12, 2017, 12:56 AM
One of the easiest and best articles about login in asp.net mvc
umair mohsinPosted Nov 7, 2017, 3:44 PM
Your reply would be helpful for me.any working example would be more appreciable.thanks. actually i am new asp.net mvc
umair mohsinPosted Nov 7, 2017, 3:43 PM
What to do if we want to show user details after successful log in details may include first name, last name, gender, username, etc
Shubham DashPosted Nov 2, 2017, 9:05 AM
Hello sir I have applied the above code but it's login in even the password is wrong ?
Emamode EruvieruPosted Sep 11, 2017, 11:34 AM
[HttpPost] public ActionResult GetIn(UserLoginView ULV, string returnUrl) { if (ModelState.IsValid) { UserManager UM = new UserManager(); string password = UM.GetUserPassWord(ULV.UserName); if (string.IsNullOrEmpty(password)) ModelState.AddModelError("", "Incorrect Password"); else { if (ULV.Password.Equals(password)) { FormsAuthentication.SetAuthCookie(ULV.UserName, false); return RedirectToAction("Welcome", "Home"); } else { ModelState.AddModelError("", "The Password is incorrect"); } } }
Abdul Amin KhanPosted Jul 13, 2017, 6:18 AM
Thank you.. Nice Article...
tizazu bayihPosted Jun 10, 2017, 8:25 AM
Is not redirect page after inserting the value of username and password at run time
rodolfo rodriguezPosted May 25, 2017, 6:35 PM
How can make the Logout part?
zia ziaPosted May 10, 2017, 7:58 AM
Are you an asp.net developer in microsoft
Prodyumna MajumderPosted Feb 16, 2017, 5:36 AM
DB_Entities db = new DB_Entities() is not getting recognized . Could you please help
piyush paprejaPosted Dec 19, 2016, 11:30 AM
Sir, How to implement session in layout.cshtml
Shweta GawkarPosted Dec 1, 2016, 12:22 AM
And how to crate custom action filter such that it will check user is logged or not if yes then it will post the form else it will redirect to login action.
Shweta GawkarPosted Dec 1, 2016, 12:06 AM
How to implement without using entity framework?
Shweta GawkarPosted Dec 1, 2016, 12:05 AM
How to do it without using Entity Frame Work?
Jaipal ReddyPosted Sep 8, 2016, 8:10 AM
Thank you Ramadoss E.
Ramadoss EPosted Sep 8, 2016, 6:41 AM
Thank you.. Nice Article...
Jaipal ReddyPosted Apr 1, 2016, 12:01 AM
Thank you Hari Shanker sir. .
Hari ShankerPosted Mar 31, 2016, 11:55 PM
Thanq Jaipal Reddy
Jaipal ReddyPosted Mar 24, 2016, 12:07 AM
Thank you Mohammad Khalid Sir. .
Mohammad KhalidPosted Mar 23, 2016, 7:28 AM
Very Simple and good article to understand MVC.
Jaipal ReddyPosted Mar 17, 2016, 12:04 AM
Thank you sir. .
Saillesh PawarPosted Mar 16, 2016, 10:55 AM
nice 1
Jaipal ReddyPosted Mar 15, 2016, 2:43 AM
Thank you sir. .
Vignesh ManiPosted Mar 14, 2016, 5:51 PM
Nice
Jaipal ReddyPosted Mar 14, 2016, 11:48 AM
Thank you sir. .
Amit Kumar SinghPosted Mar 14, 2016, 8:48 AM
Good one
Jaipal ReddyPosted Mar 14, 2016, 5:09 AM
Thank you sir. .
Mohammed IbrahimPosted Mar 14, 2016, 4:03 AM
nice
Jaipal ReddyPosted Mar 14, 2016, 1:19 AM
Thank you Sir. .
Debasis SahaPosted Mar 14, 2016, 12:47 AM
Nice share
Jaipal ReddyPosted Mar 13, 2016, 11:51 PM
Thank you Asfend Yar. . .
Asfend YarPosted Mar 13, 2016, 2:01 PM
thanks
Jaipal ReddyPosted Mar 13, 2016, 11:53 AM
Thank you kalu singh rao...
kalu singh raoPosted Mar 13, 2016, 11:42 AM
Nice...
Jaipal ReddyPosted Mar 13, 2016, 7:15 AM
Thank you Humayun Kabir Mamun
Jaipal ReddyPosted Mar 13, 2016, 7:15 AM
Thank you Sthitaprajnya Debasis.
Humayun Kabir MamunPosted Mar 13, 2016, 3:10 AM
Nice...
Sthitaprajnya Debasis NayakPosted Mar 13, 2016, 1:47 AM
Nice Article !!!