Search This Blog

Monday 1 April 2024

split FullName column to FirstName, MiddleName, LastName column in MS SQL

 DECLARE @fullname VARCHAR(60) = 'Ram Gopal Varma'

       ,@FirstName VARCHAR(20)
       ,@MiddleName VARCHAR(20)
       ,@LastName VARCHAR(20)
       ,@1stSpaceIndex INT
       ,@2ndSpaceIndex INT
       ,@3rdSpaceIndex INT
 
SET @1stSpaceIndex = CHARINDEX(' ', @fullname) -- Get 1st Space Index
SET @2ndSpaceIndex = CHARINDEX(' ', @fullname, @1stSpaceIndex + 1) --Get 2nd Space Index with start location
SET @3rdSpaceIndex = CHARINDEX(' ', REVERSE(@fullname)) -- Get 3rd Space Index using reverse fuction
 
--Get 1st name using left function
SET @FirstName = LEFT(@fullname, @1stSpaceIndex - 1) --(-1 remove the space count)
 
--Check 2nd name exists or not
IF @2ndSpaceIndex <> 0
BEGIN
       --Get 2nd name using substring function
       SET @MiddleName = SUBSTRING(@fullname, @1stSpaceIndex + 1, @2ndSpaceIndex - @1stSpaceIndex - 1)
END
 
--Get 3rd name using left & reverse function
SET @LastName = REVERSE(LEFT(REVERSE(@fullname), @3rdSpaceIndex))
 
SELECT @1stSpaceIndex AS '1stSpaceIndex'
       ,@2ndSpaceIndex AS '2ndSpaceIndex'
       ,@3rdSpaceIndex AS '3rdSpaceIndex'
 
SELECT @FirstName AS 'FirstName'
       ,@MiddleName AS 'MiddleName' 
       ,@LastName AS 'LastName' 

Results

1stSpaceIndex 2ndSpaceIndex 3rdSpaceIndex
------------- ------------- -------------
4             10            6
 
(1 row affected)
 
FirstName            MiddleName           LastName
-------------------- -------------------- --------------------
Ram                  Gopal                 Varma

(1 row affected)

Tuesday 9 June 2020

CRUD in Asp.Net MVC using C Sharp


Step 1: - Open Visual Studio 2015 => Go to File Menu => New => Project...

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application (.NET Framework) from the Web list => Type MVC_CRUD in the Name box => Click OK

Step 4: - Select MVC template from ASP.NET Templates List and Checked Add unit tests check box.





























Step 5: - Right Click on Models folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type CityViewModels.cs in the Name box => Click Add

Copy Past following code in CityViewModels.cs

public class CityViewModels
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 6: - Right Click on Models folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type DepartmentViewModels.cs in the Name box => Click Add

Copy Past following code in DepartmentViewModels.cs

public class DepartmentViewModels
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Step 7: - Right-click on Models folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type DOBValidationAttribute.cs in the Name box => Click Add

Copy Past following code in DOBValidationAttribute.cs

using System;
using System.ComponentModel.DataAnnotations;

public class DOBValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        DateTime dob = Convert.ToDateTime(value);
        if (dob <= DateTime.Now.AddYears(-18))
            return ValidationResult.Success;
        else
            return new ValidationResult(ErrorMessage);
    }
}

Step 8: - Right-click on Models folder in Solution Explorer => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type EmployeeViewModels.cs in the Name box => Click Add

Copy Past following code in EmployeeViewModels.cs

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

public class EmployeeViewModels
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Gender { get; set; }

    public string GenderName { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Date Of Birth")]
    [DOBValidation(ErrorMessage = "Date Of Birth must be 18 or above.")]
    public DateTime DOB { get; set; } = DateTime.Now.AddYears(-18);

    [Required]
    [EmailAddress]
    [Display(Name = "Email Id")]
    public string EmailId { get; set; }

    [Required]
    [StringLength(10, ErrorMessage = "Mobile number cannot be greater than 10 digit.")]
    [RegularExpression("[0-9]{10}$", ErrorMessage = "Invalid Mobile number.")]
    [Display(Name = "Mobile No")]
    public string MobileNo { get; set; }

    [Required]
    public string Department { get; set; }

    public string DepartmentName { get; set; }

    [Required]
    public string City { get; set; }

    public string CityName { get; set; }

    public List<DepartmentViewModels> Departments { get; set; }

    public List<CityViewModels> Cities { get; set; }
}

Step 9: - Right Click on Project Root folder => Add => New folder => Type name DAL
Step 10: - Right Click on DAL folder => Add => Click New Items... => Expand Visual C# from left pane => Select Code =>Select Class from middle pane => Type EmployeeContext.cs in the Name box => Click Add

Copy Past following code in EmployeeContext.cs

using MVC_CRUD.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;

public class EmployeeContext
{
    private SqlConnection _con = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
    private DataSet _dataset = null;
    private int _flag;

    public int SaveEmployee(EmployeeViewModels employee)
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_SaveEmployee";
                cmd.Connection = _con;
                cmd.Parameters.AddWithValue("@Name", employee.Name);
                cmd.Parameters.AddWithValue("@Gender", employee.Gender);
                cmd.Parameters.AddWithValue("@DOB", employee.DOB.ToString("yyyy-MM-dd"));
                cmd.Parameters.AddWithValue("@EmailId", employee.EmailId);
                cmd.Parameters.AddWithValue("@MobileNo", employee.MobileNo);
                cmd.Parameters.AddWithValue("@Department", employee.Department);
                cmd.Parameters.AddWithValue("@City", employee.City);
                _flag = cmd.ExecuteNonQuery();
                _con.Close();
            }
            return _flag;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public int UpdateEmployee(EmployeeViewModels employee)
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_UpdateEmployee";
                cmd.Connection = _con;
                cmd.Parameters.AddWithValue("@Id", employee.Id);
                cmd.Parameters.AddWithValue("@Name", employee.Name);
                cmd.Parameters.AddWithValue("@Gender", employee.Gender);
                cmd.Parameters.AddWithValue("@DOB", employee.DOB.ToString("yyyy-MM-dd"));
                cmd.Parameters.AddWithValue("@EmailId", employee.EmailId);
                cmd.Parameters.AddWithValue("@MobileNo", employee.MobileNo);
                cmd.Parameters.AddWithValue("@Department", employee.Department);
                cmd.Parameters.AddWithValue("@City", employee.City);
                _flag = cmd.ExecuteNonQuery();
                _con.Close();
            }
            return _flag;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public int DeleteEmployee(int? Id)
    {
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_DeleteEmployee";
                cmd.Connection = _con;
                cmd.Parameters.AddWithValue("@Id", Id);
                _flag = cmd.ExecuteNonQuery();
                _con.Close();
            }
            return _flag;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<EmployeeViewModels> SelectEmployeeList()
    {
        List<EmployeeViewModels> employeeList = null;
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_SelectEmployeeList";
                cmd.Connection = _con;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    _dataset = new DataSet();
                    da.Fill(_dataset);
                }
                _con.Close();
            }

            if (_dataset.Tables[0].Rows.Count > 0)
            {
                var jsonString = JsonConvert.SerializeObject(_dataset.Tables[0]);
                employeeList = JsonConvert.DeserializeObject<List<EmployeeViewModels>>(jsonString);
            }
            return employeeList;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public EmployeeViewModels SelectEmployee(int? Id)
    {
        EmployeeViewModels employee = null;
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_SelectEmployee";
                cmd.Connection = _con;
                cmd.Parameters.AddWithValue("@Id", Id);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    _dataset = new DataSet();
                    da.Fill(_dataset);
                }
                _con.Close();
            }

            if (_dataset.Tables[0].Rows.Count > 0)
            {
                var jsonString = JsonConvert.SerializeObject(_dataset.Tables[0]).Replace("[", "").Replace("]", "");
                employee = JsonConvert.DeserializeObject<EmployeeViewModels>(jsonString);
            }
            return employee;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<DepartmentViewModels> SelectDepartmentList()
    {
        List<DepartmentViewModels> departmentList = null;
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_SelectDepartmentList";
                cmd.Connection = _con;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    _dataset = new DataSet();
                    da.Fill(_dataset);
                }
                _con.Close();
            }

            if (_dataset.Tables[0].Rows.Count > 0)
            {
                var jsonString = JsonConvert.SerializeObject(_dataset.Tables[0]);
                departmentList = JsonConvert.DeserializeObject<List<DepartmentViewModels>>(jsonString);
            }

            return departmentList;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public List<CityViewModels> SelectCityList()
    {
        List<CityViewModels> cityList = null;
        try
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                _con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "proc_SelectCityList";
                cmd.Connection = _con;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    _dataset = new DataSet();
                    da.Fill(_dataset);
                }
                _con.Close();
            }

            if (_dataset.Tables[0].Rows.Count > 0)
            {
                var jsonString = JsonConvert.SerializeObject(_dataset.Tables[0]);
                cityList = JsonConvert.DeserializeObject<List<CityViewModels>>(jsonString);
            }

            return cityList;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Step 11: - Right Click on Controllers folder => Add => Controller... => Select MVC 5 Controller - Empty => Click Add => Type EmployeeController in Controller Name box => Click Add

Copy Past following code in EmployeeController.cs

using MVC_CRUD.Models;
using System.Web.Mvc;
using MVC_CRUD.DAL;
using System.Collections.Generic;
using System;

public class EmployeeController : Controller
{
    EmployeeContext dal = new EmployeeContext();

    [HttpGet]
    public ActionResult Index()
    {
        List<EmployeeViewModels> employeeList = dal.SelectEmployeeList();
        if (Request.IsAjaxRequest())
            return PartialView("_EmployeeList", employeeList);
        else
            return View(employeeList);
    }

    [HttpGet]
    public ActionResult Create()
    {
        EmployeeViewModels employee = new EmployeeViewModels();
        employee.Departments = dal.SelectDepartmentList();
        employee.Cities = dal.SelectCityList();

        return View(employee);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(EmployeeViewModels employee)
    {
        if (ModelState.IsValid)
        {
            dal.SaveEmployee(employee);
        }
        else
        {
            employee = new EmployeeViewModels();
            employee.Departments = dal.SelectDepartmentList();
            employee.Cities = dal.SelectCityList();
            return View(employee);
        }
        return RedirectToAction("Index");
    }

    [HttpGet]
    public ActionResult Edit(int? Id)
    {
        EmployeeViewModels employee = dal.SelectEmployee(Id);
        employee.Departments = dal.SelectDepartmentList();
        employee.Cities = dal.SelectCityList();
        return View(employee);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ActionName("Edit")]
    public ActionResult Edit_Post(EmployeeViewModels employee)
    {
        if (ModelState.IsValid)
        {
            dal.UpdateEmployee(employee);
        }
        else
        {
            employee = new EmployeeViewModels();
            employee.Departments = dal.SelectDepartmentList();
            employee.Cities = dal.SelectCityList();
            return View(employee);
        }
        return RedirectToAction("Index");
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult Delete(int? Id)
    {
        int result = dal.DeleteEmployee(Id);
        if (result > 0)
            return Json(new { Message = "Record deleted successfully." }, JsonRequestBehavior.AllowGet);
        else
            return Json(new { Message = "Record deletion Failed." }, JsonRequestBehavior.AllowGet);
    }
}

Step 12: - Build Project

Step 13: - To Add View for Action Method, Right Click inside the Index Action body => Click Add View… => Type Index in the View name box => Click Add
























































Copy Past following code in Index.cshtml

@model IEnumerable<MVC_CRUD.Models.EmployeeViewModels>

@{
    ViewBag.Title = "Index";
}

<h2>Employee List</h2>

<p>
    @Html.ActionLink("Create Employee", "Create")
</p>
<div class="divEmployeeListContainer">
    @Html.Partial("_EmployeeList", Model)
</div>

@section Scripts
{
    <script>
        $(document).on("click", "#Delete", function () {
            var empId = $(this).data("emp-id");
            var requestVerificationToken = $('input[name=__RequestVerificationToken]').val();
            $.post("/Employee/Delete", { "Id": empId, "__RequestVerificationToken": requestVerificationToken }, function (data, textStatus, jqXHR) {
                alert(data.Message);
                $.get("/Employee/Index", null, function (data, textStatus, jqXHR) {
                    $(".divEmployeeListContainer").empty();
                    $(".divEmployeeListContainer").html(data);
                });
            });
        });
    </script>
}

Step 14: - Expand View folder => Right Click on Employee folder => Add => View… => Type _EmployeeList in the View name box => Checked Create as a partial view checkbox => Click Add























Copy Past following code in _EmployeeList.cshtml

@model IEnumerable<MVC_CRUD.Models.EmployeeViewModels>
@Html.AntiForgeryToken()

<table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DOB)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmailId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MobileNo)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Department)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.City)
            </th>
            <th></th>
        </tr>
        @if (Model != null)
        {
            foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.HiddenFor(modelItem => item.Gender)
                        @Html.DisplayFor(modelItem => item.GenderName)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.DOB)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.EmailId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.MobileNo)
                    </td>
                    <td>
                        @Html.HiddenFor(modelItem => item.Department)
                        @Html.DisplayFor(modelItem => item.DepartmentName)
                    </td>
                    <td>
                        @Html.HiddenFor(modelItem => item.City)
                        @Html.DisplayFor(modelItem => item.CityName)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                        <input type="button" name="Delete" id="Delete" value="Delete" class=".button" data-emp-id="@item.Id" />
                    </td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="8">No Record available to display</td>
            </tr>
        }
</table>


@*@if (Model != null)
{
    var webGrid = new WebGrid(Model, rowsPerPage: 5);

    @webGrid.GetHtml(
            tableStyle: "table",
            columns: webGrid.Columns(
            webGrid.Column(columnName: "Name", header: "Name"),
            webGrid.Column(columnName: "GenderName", header: "Gender"),
            webGrid.Column(columnName: "DOB", header: "DOB"),
            webGrid.Column(columnName: "EmailId", header: "Email Id"),
            webGrid.Column(columnName: "MobileNo", header: "Mobile No"),
            webGrid.Column(columnName: "DepartmentName", header: "Department"),
            webGrid.Column(columnName: "CityName", header: "City"),
            webGrid.Column(header: "", format:
            @<text>
                <input type="hidden" name="Gender" id="Gender" value="@item.Gender" />
                <input type="hidden" name="Department" id="Department" value="@item.Department" />
                <input type="hidden" name="City" id="City" value="@item.City" />
            </text>),
            webGrid.Column(header: "", format: @<text>@Html.ActionLink("Edit", "Edit", new { id = item.Id }) </text>),
            webGrid.Column(header: "", format: @<text><input type="button" name="Delete" id="Delete" value="Delete" class=".button" data-emp-id="@item.Id" /></text>)
            ),
            mode: WebGridPagerModes.All
    )
}
else
{
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.DOB)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmailId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MobileNo)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Department)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.City)
            </th>
            <th></th>
        </tr>
        <tr>
            <td colspan="8">No Record available to display</td>
        </tr>
    </table>
}*@

Step 15: - To Add View for Action Method, Right Click inside the Create Action body => Click Add View… => Type Create in the View name box => Click Add























Copy Past following code in Create.cshtml

@model MVC_CRUD.Models.EmployeeViewModels

@{
    ViewBag.Title = "Create";
}

<h2>Create Employee</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", 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.RadioButtonFor(model => model.Gender, "M", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Male")
                @Html.RadioButtonFor(model => model.Gender, "F", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Female")
                @Html.RadioButtonFor(model => model.Gender, "O", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Other")
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Department, new SelectList(Model.Departments, "Id", "Name"), "Select Department", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.City, new SelectList(Model.Cities, "Id", "Name"), "Select City", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", 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 List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 16: - To Add View for Action Method, Right Click inside the Edit Action body => Click Add View… => Type Edit in the View name box => Click Add























Copy Past following code in Edit.cshtml

@model MVC_CRUD.Models.EmployeeViewModels

@{
    ViewBag.Title = "Edit";
}

<h2>Edit Employee</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", 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.RadioButtonFor(model => model.Gender, "M", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Male")
                @Html.RadioButtonFor(model => model.Gender, "F", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Female")
                @Html.RadioButtonFor(model => model.Gender, "O", new { htmlAttributes = new { @class = "form-control" } }) @Html.Label("Other")
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Department, new SelectList(Model.Departments, "Id", "Name"), "Select Department", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.City, new SelectList(Model.Cities, "Id", "Name"), "Select City", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Step 17: - Copy Past Connection string in the Web.config under <configuration> Section & do modification as per your DB Server.

<connectionStrings>
  <add name="Default" connectionString="server=ServerName/IP;database=MVC;uid=UserId;pwd=Password" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 18: - Expand App_Start folder => Open RouteConfig.cs file => Rename controller value to Employee

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
);

Step 19: - DB Script

Copy Past Script in SQLQuery Window and Run Script

CREATE DATABASE MVC
GO
USE MVC
GO

CREATE TABLE dbo.Employee
(
       Id INT IDENTITY
       ,Name VARCHAR(50) NOT NULL
       ,Gender CHAR(1)  NOT NULL
       ,DOB DATE  NOT NULL
       ,EmailId VARCHAR(50)  NOT NULL
       ,MobileNo VARCHAR(10)  NOT NULL
       ,Department TINYINT  NOT NULL
       ,City TINYINT  NOT NULL  
)
GO

CREATE TABLE dbo.Department
(
       Id INT IDENTITY
       ,Name VARCHAR(50) NOT NULL
)
GO
INSERT INTO dbo.Department(Name)VALUES('IT'),('Admin'),('Finance'),('Sales')
GO

CREATE TABLE dbo.City
(
       Id INT IDENTITY
       ,Name VARCHAR(50) NOT NULL
)
GO
INSERT INTO dbo.City(Name)VALUES('Mumbai'),('Delhi'),('Kolkatta'),('Chennai')
GO

CREATE PROCEDURE dbo.proc_SaveEmployee    
(   
        @Name VARCHAR(50)
       ,@Gender VARCHAR(10)
       ,@DOB VARCHAR(10)
       ,@EmailId VARCHAR(50)
       ,@MobileNo VARCHAR(10)
       ,@Department VARCHAR(20)
       ,@City VARCHAR(20)
)   
AS    
BEGIN    
    INSERT INTO dbo.Employee (Name,Gender,DOB,EmailId,MobileNo,Department,City)    
    VALUES (@Name,@Gender,@DOB,@EmailId,@MobileNo,@Department,@City)    
END
GO

CREATE PROCEDURE dbo.proc_UpdateEmployee    
(   
        @Id INT
       ,@Name VARCHAR(50)
       ,@Gender VARCHAR(10)
       ,@DOB VARCHAR(10)
       ,@EmailId VARCHAR(50)
       ,@MobileNo VARCHAR(10)
       ,@Department VARCHAR(20)
       ,@City VARCHAR(20)
)   
AS    
BEGIN    
    UPDATE dbo.Employee
       SET    Name = @Name
              ,Gender =@Gender
              ,DOB = @DOB
              ,EmailId = @EmailId
              ,MobileNo = @MobileNo
              ,Department = @Department
              ,City  = @City
    WHERE Id = @Id
END
GO

CREATE PROCEDURE dbo.proc_DeleteEmployee    
(     
   @Id INT     
)     
AS      
BEGIN     
   DELETE
   FROM dbo.Employee
   WHERE Id = @Id
END
GO

CREATE PROCEDURE dbo.proc_SelectEmployeeList
AS   
BEGIN   
    SELECT E.Id,E.Name,E.Gender
                ,CASE WHEN E.Gender = 'M' THEN 'Male'
                             WHEN E.Gender = 'F' THEN 'Female'
                             WHEN E.Gender = 'O' THEN 'Other'
                             END 'GenderName'
                ,E.DOB,E.EmailId,E.MobileNo,E.Department,D.Name'DepartmentName'
                ,E.City,C.Name'CityName'
    FROM dbo.Employee E
       INNER JOIN dbo.Department D ON E.Department = D.Id
       INNER JOIN dbo.City C ON E.City = C.Id
END
GO

CREATE PROCEDURE dbo.proc_SelectEmployee    
(     
   @Id INT     
)     
AS      
BEGIN     
    SELECT E.Id,E.Name,E.Gender
                ,CASE WHEN E.Gender = 'M' THEN 'Male'
                             WHEN E.Gender = 'F' THEN 'Female'
                             WHEN E.Gender = 'O' THEN 'Other'
                             END 'GenderName'
                ,E.DOB,E.EmailId,E.MobileNo,E.Department,D.Name'DepartmentName'
                ,E.City,C.Name'CityName'
    FROM dbo.Employee E
       INNER JOIN dbo.Department D ON E.Department = D.Id
       INNER JOIN dbo.City C ON E.City = C.Id
    WHERE E.Id = @Id
END
GO

CREATE PROCEDURE dbo.proc_SelectDepartmentList
AS   
BEGIN   
    SELECT *   
    FROM dbo.Department
END
GO

CREATE PROCEDURE dbo.proc_SelectCityList
AS   
BEGIN   
    SELECT *   
    FROM dbo.City
END
GO

ALL Done

RUN Project

Output