Search This Blog

Thursday, July 12, 2018

Part 3 MVC : How to create User Role based Login Form in MVC with help of Ajax/JQuery / How to create a custom role-based page authorization using custom Authorize filter

For Download the Code Click on Link





Part 3 : How to create User Role based Login Form in MVC with help of Ajax/JQuery
(How to create a custom role-based page authorization using custom Authorize filter
)
In This You will learn how to create a database using MS SQL Server. We also get knowledge on ASP.NET MVC,  Entity Framework, basic of jQuery and AJAX. And we going to create pages User registration, User Login, User Profile and Admin page where user can modify, add and delete information depending on Authorization.


Overview MVC 

In MVC when a user request a page it will pass control to the Controller ,then process data when necessary and returns a Model to the View for the user to see.
In MVC we have 3 basic components
1.    Models(M)
2.    Controllers(C)
3.    Views(V)

What are Models?

It implements the logic for the application domain data. Often, model objects retrieved and store model state in database. Basically we develop business rules in this module. 

What are Controllers?

This component handles user interaction, work with the model, and ultimately select a view to render UI.

What are Views?

This components is display the user interface (UI), typically this UI is created from the model.
Let’s start our Example.
First we will create database in Ms Sql.
Query for the DB


CREATE DATABASE BookStore
Go
USE [BookStore]
 GO




CREATE TABLE [dbo].[Department](
[DepartmentID] [int] IDENTITY(1,1) NOT NULL,
[Department] [varchar](50) NULL,
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED 
(
[DepartmentID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO





CREATE TABLE [dbo].[UsersLogin](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Username] [nvarchar](50) NOT NULL,
[Password] [nvarchar](max) NOT NULL,
[Attemped] [int] NOT NULL,
[LastLogin] [datetime] NULL,
[RegDate] [datetime] NOT NULL DEFAULT (getdate()),
PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


CREATE TABLE [dbo].[UserDetail](
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Gendar] [varchar](10) NULL,
[DepartmentID] [int] NULL CONSTRAINT [DF_UserDetail_DepartmentID]  DEFAULT ((1)),
[Email] [varchar](100) NULL,
 CONSTRAINT [PK_UserDetail] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[UserDetail]  WITH CHECK ADD  CONSTRAINT [FK_UserDetail_Department] FOREIGN KEY([DepartmentID])
REFERENCES [dbo].[Department] ([DepartmentID])
GO

ALTER TABLE [dbo].[UserDetail] CHECK CONSTRAINT [FK_UserDetail_Department]
GO

ALTER TABLE [dbo].[UserDetail]  WITH CHECK ADD  CONSTRAINT [FK_UserDetail_UsersLogin] FOREIGN KEY([UserID])
REFERENCES [dbo].[UsersLogin] ([Id])
GO

ALTER TABLE [dbo].[UserDetail] CHECK CONSTRAINT [FK_UserDetail_UsersLogin]
GO


CREATE TABLE [dbo].[UserRole](
[RoleID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NOT NULL,
[RoleName] [nvarchar](50) NULL,
[Description] [nvarchar](150) NULL,
 CONSTRAINT [PK_UserRole] PRIMARY KEY CLUSTERED 
(
[RoleID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[UserRole]  WITH CHECK ADD  CONSTRAINT [FK_UserRole_UsersLogin] FOREIGN KEY([UserID])
REFERENCES [dbo].[UsersLogin] ([Id])
GO

ALTER TABLE [dbo].[UserRole] CHECK CONSTRAINT [FK_UserRole_UsersLogin]
GO


CREATE TABLE [dbo].[UserRoleDetails](
[RoleDetailID] [int] IDENTITY(1,1) NOT NULL,
[RoleID] [int] NULL,
[RoleDetail] [varchar](50) NULL,
[IsActive] [bit] NULL CONSTRAINT [DF_UserRoleDetails_IsActive]  DEFAULT ((1)),
[RoleCreatedByUserID] [int] NULL,
[RoleCreatedDate] [datetime] NULL CONSTRAINT [DF_UserRoleDetails_RoleCreatedDate]  DEFAULT (getdate()),
 CONSTRAINT [PK_UserRoleDetails] PRIMARY KEY CLUSTERED 
(
[RoleDetailID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[UserRoleDetails]  WITH CHECK ADD  CONSTRAINT [FK_UserRoleDetails_UserRole] FOREIGN KEY([RoleID])
REFERENCES [dbo].[UserRole] ([RoleID])
GO

ALTER TABLE [dbo].[UserRoleDetails] CHECK CONSTRAINT [FK_UserRoleDetails_UserRole]
GO

ALTER TABLE [dbo].[UserRoleDetails]  WITH CHECK ADD  CONSTRAINT [FK_UserRoleDetails_UsersLogin] FOREIGN KEY([RoleCreatedByUserID])
REFERENCES [dbo].[UsersLogin] ([Id])
GO

ALTER TABLE [dbo].[UserRoleDetails] CHECK CONSTRAINT [FK_UserRoleDetails_UsersLogin]
GO


CREATE TABLE [dbo].[NoticeBoard](
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[Body] [varchar](max) NULL,
[PostedDate] [datetime] NULL,
 CONSTRAINT [PK_ NoticeBoard] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[NoticeBoard]  WITH CHECK ADD  CONSTRAINT [FK_NoticeBoard_UsersLogin] FOREIGN KEY([UserID])
REFERENCES [dbo].[UsersLogin] ([Id])
GO

ALTER TABLE [dbo].[NoticeBoard] CHECK CONSTRAINT [FK_NoticeBoard_UsersLogin]
GO


Now Move to Visual Studio.
Now create Project in MVC
Open Visual Studio. (in this Case we are using VS 2017)
Create New Project under MVC with Empty Template and with MVC Enabled.
Name it StoreManagementSystem


First Add _Layout.cshtml and _ViewStart file so that we can use our demo in Maser Detail Page Layout.

Add directory to view folder and name it Shared
Create View by right click on shared folder àAddàViewàname _layout
Add Script and Content Folder in your project
Now add partial view
Add _viewstart.cshtml partial view in view folder

Now we are going to create Data Entity Model

For this
First create 3 Folder in Models
DataEntity
ViewProperties
ViewMethod

Now we are going to create Data Entity inside of DataEntity Folder
Right click on DataEntity Folderàaddànew itemà in data select ADO.Net Entity Data Model.
Name it BookModel.
Follow the wizard.

Now we Entity framework has been created but we want to create view from our own model so let’s create our Model add class file to ViewPropeties folder
Say UserPropertiesModel

For SignUP we are going to use Model UserPropertiesModel

public class RegisterUser
    {
        [Key]
        public int UserID { get; set; }
        public int RoleID { get; set; }
        public string RoleName { get; set; }
        [Required(ErrorMessage = "User Name Required")]
        [Display(Name = "User Name")]
        public string UserName { get; set; }
        [Required(ErrorMessage = "Password Required")]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [Required(ErrorMessage = "First Name Required")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "Last Name Required")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        public string Gender { get; set; }
        [RegularExpression(@"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
        public string Email { get; set; }

    }


The attributes “Required” and “DisplayName”  is called Data Annotations. Data annotations are attribute classes that lives under System.ComponentModel.DataAnnotations namespace that you can use to decorate classes or properties to enforce pre-defined validation rules. 

For more information about Data Annotations then you can refer this article from MSDN: Data Annotations or Google it.

Now we are going to create method for the above properties so that user can ADD, EDIT, READ,DELETE data from database through view by using data Entity
So now we add class in ViewMethod folder and name it. MethodManager
 Add Method
public bool checkUser(string UserName)
        {
            using (StoreDBContext DB = new StoreDBContext())
            {
                return DB.UsersLogins.Where(m => m.Username.Equals(UserName)).Any();
            }
        }

        public void AddUserAccount(RegisterUser registerUser)
        {

            using (StoreDBContext  db = new StoreDBContext ())
            {

                UsersLogin usersLogin  = new UsersLogin ();
                usersLogin.Username = registerUser.UserName;
                usersLogin.Password = registerUser.Password;
                usersLogin.RegDate  = DateTime.Now;
                usersLogin.LastLogin = DateTime.Now;
                usersLogin.Attemped = 0;
                db.UsersLogins.Add(usersLogin);
                db.SaveChanges();

                UserDetail userDetail = new UserDetail();
                userDetail.UserID = usersLogin.Id ;
                userDetail.FirstName = registerUser.FirstName;
                userDetail.LastName = registerUser.LastName;
                userDetail.Gendar = registerUser.Gender;
                userDetail.Email = registerUser.Email;
                db.UserDetails.Add(userDetail);
                db.SaveChanges();


                if (registerUser.RoleID > 0)
                {
                    UserRole userRole = new UserRole();
                    userRole.RoleID = registerUser.RoleID;
                    userRole.UserID = registerUser.UserID;
                    db.UserRoles.Add(userRole);
                    db.SaveChanges();
                }


            }


        }

Now we have Model and Entity is ready now we need to create Controller
So , Add Empty controller UserLog

If every things is fine then redirect the users to the “Welcome.cshtml”

  Now add another Controller and name it as "HomeController". This control will be our default controller also
Attributes [Authorize] Check authorization

Now add view for both index and welcome action methods of Home controller
Right click on ActionResult Index() à click on add view àcheck Layout pageà Click on ADD
Now we need to action link to Login method so that user cans signup
For this use html helper code
@Html.ActionLink("Register Now!", "Register", "UserLog")
Now we will create Welcome view and signup view for UserLog controller
Signup View must be strongly-type view  so create it.
View Name : Register
Template : Create
Model class: Register (BookStoreDemo.Models.ViewProperties)
è Create view.


Give link to get back to Home

Html mark up of Register.cshtml
@model StoreManagementSystem.Models.PropertiesForView.RegisterUser

@{
    ViewBag.Title = "RegisterUsr";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>RegisterUsr</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
   
    <div class="form-horizontal">
        <h4>RegisterUser</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
       
        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> {
                              new SelectListItem { Text = "Male", Value = "M" },
                              new SelectListItem { Text = "Female", Value = "F" } },
                              new { @class = "form-control" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to Home", "Index","Home")
</div>

Markup html for index of home/index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<div>
@Html.ActionLink("Register Now!", "Register", "UserLog")
</div>

Markup html for index of home/index.cshtml

@{
    ViewBag.Title = "Welcome";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Welcome <b>@Context.User.Identity.Name</b> </h2>



Now it time to see result
Let’s run application




Now After registering User we need to a write code for login.
How to create a custom role-based page authorization using custom Authorize filter
Please Watch Next Blog and video Part 4 MVC

No comments:

Post a Comment