Sunday, 22 October 2017

ASP.NET MVC LOGIN

Project Overview:
  • HomeController.cs
  1. Index() -> load default view of the HomeController. Where view is located at Views->Home->index.cshtml
  2. Index(LoginModel model)-> This received the data input by the user from our login form using a POST request.This return default view of the Controller which is the login form if the login details is incorrect or redirect to the landing page if successfully authenticated.
  3. AccountVerification()-> This function return boolean(true or false). This check the login credential if it is valid or not.
  4. Welcome_Page()-> This call’s the landing view if the user is successfully login.
  • LoginModel()-> This is a class where properties are being declared. (public string Email{get;set}). We will use this model to bind with our login view form.
  • chtml-> This is the Default view of Home Controller (Location Views->Home->Index.cshtml.
Welcome_Page.cshtml -> view for Welcome_Page ActionResult this serve as our UserInterface for our landing page.(Location Views->Home->Welcome_Page.cshtml)
Project output:
MVC Login Form
Let’s Start:
Note: Name your project as Simple MVC Login implementation
First create new project in Visual Studio 2013 using a default MVC Template. If this is your first time to create one visit this blog for easy instruction in creating a project How to start with Asp.Net MVC application.
After successfully creating a project go to solution explorer and navigate to Model folder and add new class for our model. Right click on Model folder choose addthen select Class.
Add Model
Name your class as LoginModel.
Name class as LoginModel
Open your LoginModel class and copy and paste code below:
LoginModel.cs Code:
  • Declare Email and password properties and define property requirements.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace Simple_MVC_Login_implementation.Models
{
    public class LoginModel
    {
        [Required]
        [Display(Name="Email")]
        public string  Email { get; set; }
        
        [Required]
        [DataType(DataType.Password)]
        [Display(Name="Password")]
        public string  Password { get; set; }
    }
}

Note:
  • using System.ComponentModel.DataAnnotations; -> This is responsible for setting attribute and requirements for your properties. Ex.  [Required]
Next, go to Controller folder and open file HomeController. HomeController is the default controller for generating the default view or User Interface of your web application. This is where we put all the Process we will need for the project.
Controller
Replace the code from your HomeController with the code below.
Home Controller Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Simple_MVC_Login_implementation.Models;
namespace Simple_MVC_Login_implementation.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            if (AccountVerification(model.Email, model.Password))
            {
                return RedirectToAction("Welcome_Page",model);
            }
            else
            {
                ModelState.AddModelError("", "Invalid Input Details");
            }
            return View();    
        }
        public bool AccountVerification(string Email,string password)
        {
            bool result = false;
            if (Email == "test@gmail.com" && password == "12345")
            {
                result = true;
            }
            return result;
        }
        public ActionResult Welcome_Page(LoginModel model)
        {
            return View(model);
        }
       
    }

}


HomeController function details:
  • Index() -> This return Default view of HomeController which is our Login Form
  •  Index(LoginModel model) – > This receive model data from our view  (Login Form) using a post request. It also redirects the page to our welome_page view if credential is successfully validated.
  • AccountVerification(string Email,string password) – > This function use to verify if email and password match to your valid credential.
  • ModelState.IsValid -> Controller properties that check model property state.
Index.cshtml Code:
Output:
MVC Login Form
Open your HomeController default view which is index.cshtml located at your solution explorer Views->Home->Index.cshtml.
View Folder
To bind our Model to our Login form use html helper to generate your form.
Copy and paste code below to your index.cshtml.
  • @using Simple_MVC_Login_implementation.Models -> access model properties.
  • @model LoginModelBind LoginModel to our View.

Code below creates a simple login form design.
@model LoginModel
@{
    ViewBag.Title = "Home Page";
}
<div class="row">
    <br/>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-horizontal",role="form" }))
    {
        <fieldset>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })   <!--Enable Data Anotation-->
            <div class="form-group">
                @Html.LabelFor(m => m.Email, new { @class = "col-lg-2 control-label"})
                <div class="col-lg-10">
                    @Html.TextBoxFor(m => m.Email, new { @class = "form-control"})
                    @Html.ValidationMessageFor(m => m.Email, "", new { @class="text-danger"}) <!Display of Error Notification-->
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.Password, new { @class = "col-lg-2 control-label"})
                <div class="col-lg-10">
                 @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                 @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })<!Display of Error Notification-->
                </div>
            </div>
            <div class="form-group">
                <div class="col-lg-10 col-lg-offset-2">
                    <button type="submit" class="btn btn-primary">Login</button>
                </div>
            </div>
        </fieldset>
    }
</div>

Lastly, create a landing page or welcome page for your application. This will be displayed after a user has successfully validated his credentials.
To add new View, from your solution explorer right click on the Home folder inside the views folder and choose Add then select MVC 5 View Page with Layout (Razor).
Manual adding of View
Then choose layout for your view.
Name View
Then choose layout for your view.
Choose layout
Open Welcome_Page view. Copy and paste code below:
Welcome_page
Welcome_Page Code:
  • Display welcome message including the email used to log in.
@using Simple_MVC_Login_implementation.Models
@model LoginModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<div class="jumbotron">
    <h2>Welcome To My Page!</h2>
    <h3>You are Log in as @Model.Email</h3>
</div>
Output:

SQL Stored Procedures using ASP.NET MVC APPLICATION

OUTPUT VIEW:
Project File structure:

Index.cshtml

This file is responsible for your User Interface design. In ASP.NET MVC framework in every controller there is always a specific views associated with it. In this case we are using HomeController so the folder from Views->Home->index.cshtml is our main view. Navigate to this file and copy and paste code below.
User Interface
 Note:
  • <script src=”~/Scripts/jquery-1.10.2.min.js”></script> -> include JQuery Script from Scripts folder
  • <script src=”~/Scripts/function.js”></script> -> include function.js Script
Code:
@{

    ViewBag.Title = "Basic function";

}

<div class="row">

    <div class="body-content">

        <div class="panel panel-default">

            <div class="panel-heading"><h4>Sample Project</h4></div>

            <div class="panel-body">

                <table id="data" class="table table-striped table-hover"></table>

            </div>

            <div class="panel-footer">

            </div>

        </div>

    </div>

</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script src="~/Scripts/function.js"></script>

function.cs

To modularize project I created a separate class use to connect to our store procedure. This is where all code associated to the database are found. I also created a folder called Service where I put this class.
To create a folder right click on your project name and choose Add to show all available option, then selects New Folder. Name your folder as Service.
Create new class name function.cs by right clicking on the folder you have just created. Then Select Add and choose class.

Add Class
Name your class as function.cs
Open the file you have just created and copy the code below.
Service Folder
To manually view Database Connection string visit this blog content How to view Connection String in Visual Studio
Code:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data;

using System.Data.SqlClient;


namespace Basic_Function.Service

{
    public class function

    {
        string Sqlconnection = "Data Source=PROG-RA;Initial Catalog=basicfunction;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";

        public DataSet SelectListing()

        {
            DataSet ds = new DataSet();

            using (SqlConnection conn = new SqlConnection(Sqlconnection))

            {

                SqlCommand cmd = new SqlCommand("SelectFromTable", conn);

                SqlDataAdapter da = new SqlDataAdapter(cmd);

                da.Fill(ds);

            }

            return ds;
        }

    }

}
Note: 
  • SelectFromTable -> Name of Stored procedure we created from the previous tutorial. To view visit this blog Creating Stored Procedure.

HomeController.cs

This is the default Controller generated during the creation of project. We will use this as our main controller for this project. Navigate to this file and copy and paste code shown below.
Controller folder
Note:
  • Service.function myservice = new function(); -> use to access our method from service-> function.cs class.
  • Basic_Function -> Project Name
  • Service -> Folder name where I created my function.cs
  • function -> class Name

Code:
using Basic_Function.Service;

using Newtonsoft.Json;

using System;

using System.Collections.Generic;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace Basic_Function.Controllers

{
    public class HomeController : Controller

    {
          Basic_Function.Service.function myservice = new function();


        public ActionResult Index()

        {

            return View();

        }

        public ActionResult SelectListing()

        {

        DataSet ds = new DataSet();

        DataTable dt = new DataTable();

        ds = myservice.SelectListing();

        dt = ds.Tables[0];

        String jsonResult = JsonConvert.SerializeObject(dt); 

        return Json(jsonResult, JsonRequestBehavior.AllowGet);

        }

    }

}

function.js

This script is used to update data to our html table in view. To create script file right click on the Scripts folder, Select Add then click on JavaScript File.
Add JavaScript File
Name your script as function.js
Script Name
Navigate to your file and copy and paste code below.
Script Folder
Note:  “/Home/SelectListing”
  • Home-> Controller name
  • SelectListing-> Method from HomeController
Code:
var Controller_url = { SelectListing: '/Home/SelectListing' };
$(document).ready(function () {

    var select = $(function () {

        $.ajax({

            url: Controller_url.SelectListing,  //Address to controller

            type: 'GET',

            cache: false,

            success: function (list) {

                var parse_list = JSON.parse(list);

                $("#data").html(table(parse_list)); //Fill Table from Database

            }

        });

    });

});

function table(data) // Javascript function for Table template  

{

    var result = "";

    result += "      <thead>";

    result += "                      <tr>";

    result += "                          <th>itemNo</th>";

    result += "                          <th>FirstName</th>";

    result += "                          <th>LastName</th>";

    result += "                          <th>Address</th>";

    result += "                          <th>Contact Person</th>";

    result += "                          <th>Contact No.</th>";

    result += "                      </tr>";

    result += "                  </thead>";

    result += "                  <tbody>";

    for (var i = 0; i < data.length; i++) {

        result += "          <tr>";

        result += "              <td>" + (Number(i) + Number(1)) + "</td>";

        result += "              <td>" + data[i].FirstName + "</td>";

        result += "              <td>" + data[i].LastName + "</td>";

        result += "              <td>" + data[i].Address + "</td>";

        result += "              <td>" + data[i].Contact_Person + "</td>";

        result += "              <td>" + data[i].Contact_Number + "</td>";

        result += "          </tr>";

    }

    result += "";

    result += "          </tbody>";

    return result;

}
To run your project simply hit f5 button from your keyboard to run in debugging mode or hit Ctrl + f5 to run without debugging mode.

React Hooks - custom Hook

  v CustomHook Ø React allows us to create our own hook which is known as custom hook. Example – 1 localStorage Demo Step-1 Create ...