Search This Blog

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

Sunday, 8 December 2019

Validate nested class in MVC with Validator.TryValidateObject()

using System.ComponentModel.DataAnnotations;


public class ValidateModel
{
    static string result = string.Empty;
    public static string Validate(object obj)
    {
        var context = new ValidationContext(obj, serviceProvider: null, items: null);
        var results = new List<ValidationResult>();
        var isValid = Validator.TryValidateObject(obj, context, results, true);
        if (!isValid)
            foreach (var validationResult in results)
                result += validationResult.ErrorMessage;
        foreach (var prop in obj.GetType().GetProperties())
        {
            if (prop.PropertyType == typeof(string) || prop.PropertyType.IsValueType) continue;
            var value = prop.GetValue(obj);
            if (value == null) continue;
            var isEnumerable = value as IEnumerable;
            if (isEnumerable == null)
                Validate(value);
            else
                foreach (var nestedModel in isEnumerable)
                    Validate(nestedModel);
        }
        return result;
    }
}

Note:- 
MVC ModelBinder is doing all complex type DataAnnotations validation itself when you checked ModelState.IsValid in the action but it's failed when you pass the object instead of model.

In that case, you need to call the Validator.TryValidateObject() function but it's also failed to validate the complex/nested class DataAnnotations.

The above example is the solution for overcome to this issue using recursive function call.


=>Sample Model
public class RegistrationRequest
{
    public object body { get; set; }
}
public class Registration
{
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    [Required]
    public string LastName { get; set; }
    public Address address { get; set; }
    public List<PastHistory> pastHistory { get; set; }
}
public class Address
{
    [Required]
    public string Address1 { get; set; }
    [Required]
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    [Required]
    public string State { get; set; }
    [Required]
    public string City { get; set; }
    [Required]
    public string Pincode { get; set; }
}
public class PastHistory
{
    [Required]
    public string ComapnyName { get; set; }
}

=>Sample Controller
[HttpPost]
public HttpResponseMessage Registration(RegistrationRequest reg)
{
    Registration registration = JsonConvert.DeserializeObject<Registration>(reg.body.ToString());

    string validateResult = ValidateModel.Validate(registration);
    if (!string.IsNullOrEmpty(validateResult))
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, validateResult);
    else
        return Request.CreateResponse(HttpStatusCode.OK);
}

=>Sample JSON
   "body":{ 
      "Id":"1",
      "FirstName":"Ram",
      "MiddleName":"",
      "LastName":"",
      "Address":{ 
         "Address1":"",
         "Address2":"",
         "Address3":"",
         "State":"",
         "City":"",
         "Pincode":""
      },
      "PastHistory":[ 
         { 
            "ComapnyName":""
         }
      ]
   }
}



How to get all Errors from modelState in ASP.Net MVC?


[HttpPost]
public HttpResponseMessage Registration(RegistrationRequest reg)
{
    if (ModelState.IsValid)
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    IEnumerable<string> errors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));
    string strErrors = string.Join("; "errors);

    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, strErrors);
}


OR


[HttpPost]
public HttpResponseMessage Registration(RegistrationRequest reg)
{
    if (ModelState.IsValid)
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }

    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}

Saturday, 7 December 2019

OR condition in regular expression

=>Web API
using System.ComponentModel.DataAnnotations;

[RegularExpression(@"^(Y)|(N)$", ErrorMessage = "IsHandicap can only be Y or N.")]
public string IsHandicap{ getset; }

=>C Sharp
using System.Text.RegularExpressions;


string regex = @"^(Y)|(N)$";
string inputString = "Y";
Match match = Regex.Match(inputString, regex);

=>Java Script
<script>
    function Validate() {
        var text = document.getElementById("TextBox1").value;
        var pattern = "^(Y)|(N)$";
        var result = text.match(pattern);
        if (!result)
            alert("IsHandicap can only be Y or N.");
    }
</script>

<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return Validate();" />


Note:- Input string only valid when IsHandicap field value "Y" and "N".


[] - Find any character matching between in the square brackets.
() - Find matching character or word in the brackets.

Regular expression for mobile number with fix country code

=>Web API
using System.ComponentModel.DataAnnotations;

[RegularExpression(@"^(91)?\d{10}$", ErrorMessage = "invalid country code or mobile no.")]   
public string mobileno { getset; }

=>C Sharp

using System.Text.RegularExpressions;

string regex = @"^(91)?\d{10}$";
string inputString = "919876543210";
Match match = Regex.Match(inputString, regex);

=>Java Script
<script>
    function Validate() {
        var text = document.getElementById("TextBox1").value;
        var pattern = "^(91)?\d{10}$";
        var result = text.match(pattern);
        if (!result)
            alert("invalid country code or mobile no.");
    }
</script>

<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return Validate();" />


Note:- Input string only valid when mobile no passed with Indian country code i.e. 91.

Saturday, 30 November 2019

How to remove last comma from string in sql server


DECLARE @STRING VARCHAR(50) = 'ABC,XYZ,'

SELECT IIF(CHARINDEX(',',REVERSE(@STRING))=1,LEFT(@STRING,LEN(@STRING)-1),@STRING)

OR

SELECT CASE 
           WHEN CHARINDEX(',',REVERSE(@STRING))=
           THEN LEFT(@STRING,LEN(@STRING)-1) 
           ELSE @STRING 
       END