Tuesday, January 9, 2018

Create login form and maintain authenticated user’s detail in MVC application

In this artic article I am going to explain how to create login form and maintain authenticated user’s detail in MVC application.

Description:
I want to create login form and maintain the authenticated user’s detail in application. I am using Tempdata to maintain the user’s detail.

Implementation:

Model:

using System;
    using System.Collections.Generic;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    public partial class Login
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "Please enter username")]
        [DisplayFormat(ConvertEmptyStringToNull = true)]
        [Display(Name = "Username")]

        public string Username { get; set; }
        [Required(ErrorMessage = "Please enter password")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Confirm password")]
        [Required(ErrorMessage = "Please enter confirm password")]
        [DataType(DataType.Password)]
       
public string Confirmpwd { get; set; }
      
 public Nullable<bool> Is_Deleted { get; set; }
    }

Add controller
Add empty controller to project. Create following actions Index, dashboard and logout. Index action is used for login, after login user is redirected to Dashboard action and logout action clear the loged in users detail.

Complete code of Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2017.Models;
using System.Security.Cryptography;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web.Security;
namespace mvcapplication2017.Controllers
{  
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        DemoEntities db = new DemoEntities();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(Login objlogin)
        {
         if (ModelState.IsValidField("Username") && ModelState.IsValidField("Password"))
                {
                    var login = db.Logins.Where(u => u.Is_Deleted == false && u.Username.Equals(objlogin.Username) && u.Password.Equals(objlogin.Password)).FirstOrDefault();
                    if (login != null)
                    {
                        TempData["user"] = login.Username; TempData.Keep("user");
                        return RedirectToAction("dashboard");
                    }
                    else
                    {
                        TempData["msg"] = "<script>alert('Username and Password does not match');</script>";
                    }
                }         
            return View(objlogin);
        }
        public ActionResult dashboard()
        {
            if (TempData["user"]==null)
            {
                return RedirectToAction("index");
            }          
            return View();
        }      
        public ActionResult LogOut()
        {
            TempData.Remove("user");
            return RedirectToAction("index","login");
        }
      
    }
}


Add View
Add view for Index and dashboard action.

Complete source of Index.cshtml :

@model MvcApplication2017.Models.Login
@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "login", FormMethod.Post))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Login</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Username)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Username)            
            @Html.ValidationMessageFor(model => model.Username)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>
        <p>
            <input type="submit" value="Login" />
        </p>
    </fieldset>
}
@Html.Raw(TempData["msg"])

    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


Complete source of Dashboard.cshtml :

@{
    ViewBag.Title = "dashboard";
    TempData.Keep("user");
}

<div style="width:auto;float:right">
    @if (@TempData["user"] != null)
    {
     <span>Welcome : </span> @TempData["user"<span> | </span> @Html.ActionLink("Log Out", "Logout", "login")
    }
    else
    {
        @Html.ActionLink("Register", "Register", "User")
        <span> | </span>
        @Html.ActionLink("Log In", "Login", "User")
    }
</div>
<div style="text-align: center; padding-top: 50px;">
    <h3>Welcome to aspmantra</h3>
</div>



No comments:

Post a Comment