Create ASP.NET MVC Project
On the Visual Studio, create new ASP.NET MVC Web Application project
Select Empty Template and Core Reference is MVC
Create Controller
In Controllers folder, create new controller named ProductController.cs as below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LearnASPNETMVCWithRealApps.Models;
namespace LearnASPNETMVCWithRealApps.Controllers
{
public class AccountController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Login(string username, string password)
{
if (username.Equals("acc1") && password.Equals("123"))
{
Session["username"] = "username";
return View("Success");
}
else
{
ViewBag.error = "Invalid Account";
return View("Index");
}
}
[HttpGet]
public ActionResult Logout()
{
Session.Remove("username");
return RedirectToAction("Index");
}
}
}
Create View
In Views/Product folder, create new razor views as below:
Index View
Create new view named Index.cshtml as below:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Login Page</h3>
@ViewBag.error
<form method="post" action="@Url.Action("Login", "Account")">
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>Username</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Success View
Create new view named Success.cshtml as below:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Success</title>
</head>
<body>
<h3>Success Page</h3>
Welcome @Session["username"]
<br>
<a href="@Url.Action("Logout", "Account")">Logout</a>
</body>
</html>
Structure of ASP.NET MVC Project
Run Application
Access Index action in Account controller with following url: http://localhost:9596/Account/Index
Output
Test with invalid account is username: acc2 and password: 123
Output
Test with valid account is username: acc1 and password: 123.
Output
Click logout link from success page to remove session and open login page again
Output
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- ASP.NET MVC Framework Unleashed
- Programming Microsoft ASP.NET MVC (3rd Edition) (Developer Reference)
- Pro ASP.NET MVC 5 Platform
- Pro ASP.NET MVC Framework
- Professional ASP.NET MVC 5