PRACTICAL 7: PARTIAL VIEWS

CREATING A FORM USING PARTIAL VIEWS.

STEPS:
1. Create a controller > AccountController.
2. Create a new folder in Views > Account > Login.cshtml.
3. Create a file in Views > Shared > Login_Partial.cshtml.
4. In Views > Shared > _Layout.cshtml add the partial view call after </nav>.
5. Run the project and open /Account/Login.

CODE: (Controllers/AccountController.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace Layout.Controllers
{
    public class AccountController : Controller
    {

        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(string username,string password)
        {
            if(username == "admin" && password == "123")
            {
                TempData["Message"] = "Welcome Admin";
                return RedirectToAction("Index", "Home");
            }
            ViewBag.Error = "Invalid username or password";
            return View();
        }
    }
}

CODE: (Views/Shared/Login_Partial.cshtml)
@{

}
@if (User.Identity.IsAuthenticated)
{
    <p>Welcome,@User.Identity.Name!</p>
    <form asp-controller="Account" asp-action="Logout" method="post">
        <button type="submit">Logout</button>
    </form>
}
else
{
    <a asp-controller="Account" asp-action="Login">Login</a>
}

CODE: (Views/Account/Login.cshtml)
@{
    ViewData["Title"] = "Login";
}
@if (ViewBag.Error !=null)
{
    <div style="color:red">@ViewBag.Error</div>
}
<form asp-controller="Account" asp-action="Login" method="post">
    <div>
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required />
    </div>
    <br />
    <div>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required />
    </div>
    <button type="submit">Login</button>
</form>

CODE: (Views/Shared/_Layout.cshtml - only add the @await line after </nav>)
            </ul>
        </div>
    </div>
</nav>
@await Html.PartialAsync("Login_Partial")
</header>
<div class="container">
    <main role="main" class="pb-3">
        @RenderBody()
    </main>
</div>

OUTPUT:
Every page shows the Login link (partial view) below the navbar.
Login page: admin / 123 redirects to Home; any other value shows "Invalid username or password".
