Category Archives: Asp.Net MVC

Call action from button click event in Asp.Net MVC

We can call action from button click event using location.href.

<button id="btnSave" onclick="location.href='@Url.Action("Action", "Controller", new { Parameter = "Value" })'">Save</button>

Grouping data in autocomplete textbox using jquery in Asp.net MVC.

We can group data in autosuggest textbox in Asp.net MVC using jquery.

autosuggest

autosuggest

Add a input box in your View.


<div>
    @Html.TextBoxFor(m =&gt; m.Search_text, new { id = "Search_text", placeholder = "City, Airport, Place, Hotel Name", @class = "textWidth" })
</div>


Add model in your view. Creation of model will be done later.

@model MvcApplication1.Models.Search


Add style sheets in your view. we are referring some css and js files from jquery cdn.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="~/Css/StyleSheet.css" rel="stylesheet" />


Download this style sheet and add to your project and refer accordingly. Style Sheet Link
AutoSuggest.css
jQuery code for autocomplete input box. We have customized rendering part so that we can group result in input box. Grouping is done on the basis of category of content. Add this script into your view.

<script>
    $(function () {
        var searchText_Old = '';
        var CustomrenderMenu = function (Ul, item) {

            var Self = this;
            var Search_Category = null;
            var NodeCount = 0;
            $.each(item, function (index, item) {
                var li;

                if (item.category != Search_Category) {
                    Search_Category = item.category;
                    NodeCount = 1;
                    Ul.append("
&lt;li class=Header-" + Search_Category + "&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;" + Search_Category + "&lt;/li&gt;

");
                }
                li = Self._renderItemData(Ul, item);
                var liText = li.html();
                var SearchTerm = searchText_Old;
                var tag = 'b' || 'Strong',
                words = [SearchTerm] || [],
                regex = RegExp(words.join('|'), 'gi'),
                replacement = '&lt;' + tag + '&gt;$&amp;&lt;/' + tag + '&gt;';
                var liTextHighlighted = liText.replace(regex, replacement);
                li.html(liTextHighlighted);
                li.addClass("Content");
            });
            Ul.append("
&lt;li class=ui-last-line&gt;Keep typing your filter...&lt;/li&gt;

");
        };

        $('#Search_text').autocomplete({
            minlength: 3,
            source: function (request, response) {
                var SearchText = document.getElementById('Search_text').value;
                searchText_Old = SearchText;
                $('#Search_text').addClass('AutoSuggestLoader');
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    async: true,
                    url: "/Home/autoCompleteSearch",
                    data: "{Search_:'" + SearchText + "'}",
                    contentType: "application/json;characterset=utf-8",
                    success: function (result) {

                        $('#Search_text').removeClass('AutoSuggestLoader');
                        response(result);
                    },
                    error: function (result) {
                        debugger
                        $('#Search_text').removeClass('AutoSuggestLoader');
                        console.log(result);
                    }
                });
            },
            select: function (event, ui) {
                $('#Search_text').val(ui.item.label);
                return false;
            }
        })
        .focus(function () {
            $(this).autocomplete("search");
        })
        .autocomplete('instance')._renderMenu = CustomrenderMenu;
    });
</script>


Create a model class “Search” in your model folder. We have created four categories Hotel, city, airport and Place and create some dummy data.

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

namespace MvcApplication1.Models
{
    public class Search
    {
        public string label { get; set; }
        public string value { get; set; }
        public string category { get; set; }
        public string Search_text { get; set; }

        public List<string> GetCity()
        {
            List<string> objCity = new List<string>();
            objCity.Add("New Delhi");
            objCity.Add("Gurgaon");
            objCity.Add("Ghaziabad");
            objCity.Add("Mumbai");
            return objCity;
        }

        public List<string> GetAirport()
        {
            List<string> objAirport = new List<string>();
            objAirport.Add("Indira Gandhi International Airport");
            objAirport.Add("Santa Cruz Airport");
            objAirport.Add("Chhatrapati Shivaji International Airport");
            objAirport.Add("Bengaluru International Airport");
            return objAirport;
        }

        public List<string> GetPlace()
        {
            List<string> objPlace = new List<string>();
            objPlace.Add("Taj Mahal");
            objPlace.Add("Humayun's Tomb");
            objPlace.Add("Qutub Minar");
            objPlace.Add("akshardham");
            return objPlace;
        }

        public List<string> GetHotel()
        {
            List<string> objHotel = new List<string>();
            objHotel.Add("Taj Hotels");
            objHotel.Add("Oberoi Hotels");
            objHotel.Add("Redisson Hotels");
            objHotel.Add("Hyatt Hotels And Resorts");
            return objHotel;
        }


        public List<Search> SearchAutocomplete(string Search_)
        {
            List<Search> objSearchList = new List<Search>();
            List<string> objHotel = GetHotel().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            List<string> objCity = GetCity().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            List<string> objPlace = GetPlace().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            List<string> objAirport = GetAirport().Where(h => h.ToUpperInvariant().Contains(Search_.ToUpperInvariant())).ToList();
            foreach (var City in objCity)
            {
                objSearchList.Add(new Search { label = City, value = City, category = "City" });
            }
            foreach (var Airport in objAirport)
            {
                objSearchList.Add(new Search { label = Airport, value = Airport, category = "Airport" });
            }
            foreach (var Place in objPlace)
            {
                objSearchList.Add(new Search { label = Place, value = Place, category = "Place" });
            }
            foreach (var Hotel in objHotel)
            {
                objSearchList.Add(new Search { label = Hotel, value = Hotel, category = "Hotel" });
            }
            return objSearchList;
        }
    }
}


Create a controller file and put this code in your controller file. This Action return json format data.

[HttpPost]
public ActionResult autoCompleteSearch(string Search_)
{
    Search obj = new Search();
    return Json(obj.SearchAutocomplete(Search_), JsonRequestBehavior.AllowGet);
}

Note: We have used four images for category and one loader image.

airport

airport

autosuggestloader

autosuggestloader

city

city

hotel

hotel

place

place

Jquery cross domain ajax request

Jquery cross domain ajax request can be made by setting crossDomain property to true. For cross domain request we need to set some configurations in both the application’s web.config file.

<script>
    $(document).ready(function () {
        $.ajax({
            type: 'GET',
            url: 'URL',
            crossDomain: true,
            data: {},
            dataType: 'json',
            success: function (responseData, textStatus, jqXHR) {
                if (responseData != null) {
                    $("#id").html(responseData);
                }
            },
            error: function (responseData, textStatus, errorThrown) {
                $("#id").html(errorThrown);
            }
        });
    });
</script>


For cross domain ajax request we need to set max Json Length in both the application’s web.config file. Put the below lines inside the Configuration section.

<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="900000"></jsonSerialization>
      </webServices>
    </scripting>
  </system.web.extensions>


For cross domain ajax request we need to add Custom Headers. Add these Custom Headers in both the application’s web.config file. Put the below lines inside System.WebServer section.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Origin" value="Content-Type"/>
  </customHeaders>
</httpProtocol>

Error executing child request for handler ‘System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper’.

This error occurred when you are calling a child action method. And that child View does not exists or have been moved to a new location.

 @Html.Action("Child", "Home")


Here “Child” is the Action method name and “Home” is the controller name.

Asp.Net MVC CRUD Operations

This Tutorial will explain how to implement crud operations in Asp.Net with MVC Framework.

Open Visual Studio 2012. Go to create new project tab. Select Asp.Net MVC 4 web Application.
Then choose Basic Template from the template list and Razor as View engine from the list.

MVC Template

MVC Template

Now there are three pre included folders as

  • Models
  • Views
  • Controllers

Final figure we need to achieve is

MVC Data

MVC Data

Now let’s start with the model

Model

Create a class in model folder as Employee.cs

public class Employee
{
    private string _language;
    private string _gender;
    private bool _male;
    private bool _female;
    private bool _hindi;
    private bool _english;
    private bool _french;

    public Employee()
    {

    }

    [Required(ErrorMessage = "Employee Id is manadatory!")]
    [Display(Name = "Emp ID")]
    public string ID { get; set; }

    [Required(ErrorMessage = "FirstName is manadatory!")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "LastName is manadatory!")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Address is manadatory!")]
    public string Address { get; set; }

    [Required(ErrorMessage = "Language is manadatory!")]
    public string Language
    {
        get { return _language; }
        set
        {
            _language = string.Empty;
            string Comma = string.Empty;
            if (Hindi)
            {
                _language = "Hindi";
            }
            if (English)
            {
                if (!string.IsNullOrEmpty(_language))
                {
                    Comma = ",";
                }
                _language = _language + Comma + "English";
            }
            if (French)
            {
                if (!string.IsNullOrEmpty(_language))
                {
                    Comma = ",";
                }
                _language = _language + Comma + "French";
            }
        }
    }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "DOB")]
    [Required(ErrorMessage = "DOB is manadatory!")]
    public DateTime DOB { get; set; }

    public bool Male
    {
        get { return _male; }
        set
        {
            _male = value;
            Gender = "Male";
        }
    }

    public bool Female
    {
        get { return _female; }
        set
        {
            _female = value;
            Gender = "Female";
        }
    }
    public string Gender
    {
        get { return _gender; }
        set
        {
            if (Male)
            {
                _gender = "Male";
            }
            if (!Male)
            {
                _gender = "Female";
            }
        }
    }

    public bool Hindi
    {
        get { return _hindi; }
        set
        {
            _hindi = value;
            Language = "Hindi";
        }
    }

    public bool English
    {
        get { return _english; }
        set
        {
            _english = value;
            Language = "English";
        }
    }

    public bool French
    {
        get { return _french; }
        set
        {
            _french = value;
            Language = "French";
        }
    }

    [Display(Name = "Nationality")]
    public String NationalityID { get; set; }

    public virtual Nationality Nationality { get; set; }
}


Add a Nationality class file in the model folder for Nationality List

public class Nationality
{
    public string NationalityID { get; set; }

    [StringLength(50, MinimumLength = 3)]
    public string Name { get; set; }
}


Add a class file in model folder for Data Access Layer and name it EmployeeList
To get all the employee list write the below line of code in this file.

public List<Employee> GetEmployeeList(string ID)
{
    try
    {
        SqlParameter[] MyParams = new SqlParameter[1];
        MyParams[0] = new SqlParameter("@ID", ID);
        DataTable dt = SqlHelper.ExecuteDataTable(AppConstants.getConnectionString(), CommandType.StoredProcedure, "[dbo].[uspGetUser]", MyParams);
        var Employee = new List<Employee>();
        foreach (DataRow row in dt.Rows)
        {
            var obj = new Employee()
            {
                ID = (string)row["ID"],
                FirstName = (string)row["FirstName"],
                LastName = (string)row["LastName"],
                DOB = (DateTime)row["dtDOB"],
                Gender = (string)row["Gender"],
                NationalityID = (string)row["Nationality"],
                Language = ((string)row["Language"]),
                Address = (string)row["Address"],
                Male = (bool)row["Male"],
                Female = (bool)row["Female"],
                Hindi = (bool)row["Hindi"],
                English = (bool)row["English"],
                French = (bool)row["French"],
            };
            Employee.Add(obj);
        }
        return Employee;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


Note : Create your own database and table with these fields above used and procedure name it uspGetUser.
Controller

Add a new controller in the Controller folder and name it EmployeeController and choose Empty MVC Controller from the scaffolding options.

Addition of Controller

Addition of Controller

Add below line of code in the EmployeeController file.

public ActionResult Index()
{
    EmployeeList emp = new EmployeeList();
    List<Employee> objEmp = emp.GetEmployeeList(string.Empty).OrderBy(x => x.FirstName).ToList();
    return View(objEmp);
}


View
Add a new folder in Views folder and name it Employee.
Add a new View in Employee folder and name it Index.

Adding a View

Adding a View

Add below line of code in Index View.

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using MVCCrudOperations.Models;
@*<h2>Index</h2>*@
@model IEnumerable<Employee>
<h2>Employee List</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table style="width: 700px; border-collapse: collapse" border="1">
    <thead>
        <tr>
            <th>Emp ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Address</th>
            <th>Language</th>
            <th>DOB</th>
            <th>Nationality</th>
            <th>Gender</th>
            <th>Details</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
        @foreach (Employee emp in @Model)
        { 
            <tr>
                <td>@emp.ID
                </td>
                <td>@emp.FirstName
                </td>
                <td>@emp.LastName
                </td>
                <td>@emp.Address
                </td>
                <td>@emp.Language
                </td>
                <td>@Html.DisplayFor(modelitem => emp.DOB)
                </td>
                <td>@emp.NationalityID
                </td>
                <td>@emp.Gender
                </td>
                <td>@Html.ActionLink("Details", "Details", new { id = emp.ID }) </td>
                <td>@Html.ActionLink("Edit", "Edit", new { id = emp.ID }) </td>
                <td>@Html.ActionLink("Delete", "Delete", new { id = emp.ID }) </td>
            </tr>
        }
    </tbody>
</table>


Add a new View in Employee folder and name it Create.

@model MVCCrudOperations.Models.Employee

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

<h2>Create</h2>

@using (Html.BeginForm())
{
<div class="editor-label">@Html.LabelFor(model => model.ID)</div>
<div class="editor-field">@Html.EditorFor(model => model.ID) @Html.ValidationMessageFor(model => model.ID)</div>
<div class="editor-label">@Html.LabelFor(model => model.FirstName)</div>
<div class="editor-field">@Html.EditorFor(model => model.FirstName)@Html.ValidationMessageFor(model => model.FirstName)</div>
<div class="editor-label">@Html.LabelFor(model => model.LastName)</div>
<div class="editor-field">@Html.EditorFor(model => model.LastName)@Html.ValidationMessageFor(model => model.LastName)</div>
<div class="editor-label">@Html.LabelFor(model => model.Address)</div>
<div class="editor-field">@Html.EditorFor(model => model.Address)@Html.ValidationMessageFor(model => model.Address)</div>
<div class="editor-label">@Html.LabelFor(model => model.Language)</div>
<div class="editor-field">@Html.CheckBox("English", isChecked: false)@Html.LabelFor(model => model.English)@Html.CheckBox("Hindi", isChecked: false)@Html.LabelFor(model => model.Hindi)@Html.CheckBox("French", isChecked: false)@Html.LabelFor(model => model.French)</div>
<div class="editor-label">@Html.LabelFor(model => model.DOB)</div>
<div class="editor-field">@Html.EditorFor(model => model.DOB)@Html.ValidationMessageFor(model => model.DOB)</div>
<div class="editor-label">@Html.LabelFor(model => model.Nationality)</div>
<div class="editor-field">@Html.DropDownList("NationalityID", "Select Nationality")</div>
<div class="editor-label">@Html.LabelFor(model => model.Gender)</div>
<div class="editor-field">
@Html.RadioButtonFor(model => model.Male, "true")@Html.LabelFor(model => model.Male)
@Html.RadioButtonFor(model => model.Male, "false")@Html.LabelFor(model => model.Female)
</div>
<p>
<input type="submit" value="Save" />&nbsp;|&nbsp;@Html.ActionLink("Back to List", "Index")
</p> 
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" 
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" 
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/DatePickerReady.js")" 
type="text/javascript"></script>
}

}


Create View

Create View

For the Controller part
Add these lines in EmployeeController

public ActionResult Create()
{
EmployeeList emp = new EmployeeList();
ViewBag.NationalityID = new SelectList(emp.GetNationality(), "NationalityID", "Name");
return View();
}

[HttpPost]
public ActionResult Create(Employee Emp)
{
if (ModelState.IsValid)
{
EmployeeList objEmp = new EmployeeList();
objEmp.AddEmployee(Emp);
return RedirectToAction("Index");
}
return View();
}


For the Model Part
Add these lines in EmployeeList

public void AddEmployee(Employee employee)
{
try
{
SqlParameter[] MyParams = new SqlParameter[8];
MyParams[0] = new SqlParameter("@ID", employee.ID);
MyParams[1] = new SqlParameter("@FirstName", employee.FirstName);
MyParams[2] = new SqlParameter("@LastName", employee.LastName);
MyParams[3] = new SqlParameter("@Gender", employee.Gender);
MyParams[4] = new SqlParameter("@DOB", employee.DOB);
MyParams[5] = new SqlParameter("@Language", employee.Language);
MyParams[6] = new SqlParameter("@Nationality", employee.NationalityID);
MyParams[7] = new SqlParameter("@Address", employee.Address);
SqlHelper.ExecuteNonQuery(AppConstants.getConnectionString(), CommandType.StoredProcedure, "[dbo].[uspInsertUser]", MyParams);
}
catch (SqlException ex)
{
throw ex;
}
}


Add a new View in Employee folder and name it Edit.

@model MVCCrudOperations.Models.Employee

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

<h2>Edit</h2>
@using (Html.BeginForm())
{
    <div class="editor-label">@Html.LabelFor(model => model.ID)</div>
    <div class="editor-field">@Html.EditorFor(model => model.ID) @Html.ValidationMessageFor(model => model.ID)</div>
    <div class="editor-label">@Html.LabelFor(model => model.FirstName)</div>
    <div class="editor-field">@Html.EditorFor(model => model.FirstName)@Html.ValidationMessageFor(model => model.FirstName)</div>
    <div class="editor-label">@Html.LabelFor(model => model.LastName)</div>
    <div class="editor-field">@Html.EditorFor(model => model.LastName)@Html.ValidationMessageFor(model => model.LastName)</div>
    <div class="editor-label">@Html.LabelFor(model => model.Address)</div>
    <div class="editor-field">@Html.EditorFor(model => model.Address)@Html.ValidationMessageFor(model => model.Address)</div>
    <div class="editor-label">@Html.LabelFor(model => model.Language)</div>
    <div class="editor-field">@Html.CheckBox("English", isChecked: Model.English)@Html.LabelFor(model => model.English)@Html.CheckBox("Hindi", isChecked: Model.Hindi)@Html.LabelFor(model => model.Hindi)@Html.CheckBox("French", isChecked: Model.French)@Html.LabelFor(model => model.French)</div>
    <div class="editor-label">@Html.LabelFor(model => model.DOB)</div>
    <div class="editor-field">@Html.EditorFor(model => model.DOB)@Html.ValidationMessageFor(model => model.DOB)</div>
    <div class="editor-label">@Html.LabelFor(model => model.Nationality)</div>
    <div class="editor-field">@Html.DropDownList("NationalityID", "Select Nationality")</div>
    <div class="editor-label">@Html.LabelFor(model => model.Gender)</div>
    <div class="editor-field">
        @Html.RadioButtonFor(model => model.Male, "true")@Html.LabelFor(model => model.Male)
        @Html.RadioButtonFor(model => model.Male, "false")@Html.LabelFor(model => model.Female)
    </div>
    <p>
        <input type="submit" value="Save" />&nbsp;|&nbsp;@Html.ActionLink("Back to List", "Index")
    </p> 
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" 
        type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" 
        type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/DatePickerReady.js")" 
        type="text/javascript"></script>
    }

}


For Controller Part

public ActionResult Edit(String id = "")
{
    EmployeeList emp = new EmployeeList();
    List<Employee> objEmp = emp.GetEmployeeList(id).OrderBy(x => x.FirstName).ToList();
    ViewBag.NationalityID = new SelectList(emp.GetNationality(), "NationalityID", "Name", objEmp.FirstOrDefault().NationalityID);
    return View(objEmp.FirstOrDefault());
}

[HttpPost]
public ActionResult Edit(Employee Emp)
{
    if (ModelState.IsValid)
    {
        EmployeeList objEmp = new EmployeeList();
        objEmp.AddEmployee(Emp);
        return RedirectToAction("Index");
    }
    return View();
}


Add a new View in Employee folder and name it Details.

@model MVCCrudOperations.Models.Employee

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

<h2>Details</h2>
@using (Html.BeginForm())
{
    <div class="display-label">@Html.DisplayNameFor(model => model.ID)</div>
    <div class="display-label">@Html.DisplayFor(model => model.ID) </div>
    <div class="display-label">@Html.DisplayNameFor(model => model.FirstName)</div>
    <div class="display-label">@Html.DisplayFor(model => model.FirstName)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.LastName)</div>
    <div class="display-label">@Html.DisplayFor(model => model.LastName)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Address)</div>
    <div class="display-label">@Html.DisplayFor(model => model.Address)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Language)</div>
    <div class="display-label">@Html.DisplayFor(model => model.Language)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.DOB)</div>
    <div class="display-label">@Html.DisplayFor(model => model.DOB)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Nationality)</div>
    <div class="display-label">@Html.DisplayFor(model => model.NationalityID)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Gender)</div>
    <div class="display-label">@Html.DisplayFor(model => model.Gender)</div>
    <div>@Html.ActionLink("Edit", "Edit", new { id =  Model.ID })&nbsp|&nbsp;@Html.ActionLink("Back to List", "Index")</div>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" 
        type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" 
        type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/DatePickerReady.js")" 
        type="text/javascript"></script>
    }
}


For Controller Part

public ActionResult Details(String id = "")
{
    EmployeeList emp = new EmployeeList();
    List<Employee> objEmp = emp.GetEmployeeList(id).OrderBy(x => x.FirstName).ToList();
    return View(objEmp.FirstOrDefault());
}


Add a new View in Employee folder and name it Delete.

@model MVCCrudOperations.Models.Employee

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

<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
@using (Html.BeginForm())
{
    <div class="display-label">@Html.DisplayNameFor(model => model.ID)</div>
    <div class="display-label">@Html.DisplayFor(model => model.ID) </div>
    <div class="display-label">@Html.DisplayNameFor(model => model.FirstName)</div>
    <div class="display-label">@Html.DisplayFor(model => model.FirstName)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.LastName)</div>
    <div class="display-label">@Html.DisplayFor(model => model.LastName)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Address)</div>
    <div class="display-label">@Html.DisplayFor(model => model.Address)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Language)</div>
    <div class="display-label">@Html.DisplayFor(model => model.Language)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.DOB)</div>
    <div class="display-label">@Html.DisplayFor(model => model.DOB)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Nationality)</div>
    <div class="display-label">@Html.DisplayFor(model => model.NationalityID)</div>
    <div class="display-label">@Html.DisplayNameFor(model => model.Gender)</div>
    <div class="display-label">@Html.DisplayFor(model => model.Gender)</div>
    <p>
         <input type="submit" value="Delete" />&nbsp;|&nbsp;@Html.ActionLink("Back to List", "Index")
    </p>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" 
        type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.min.js")" 
        type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/DatePickerReady.js")" 
        type="text/javascript"></script>
    }

}


For Controller Part

public ActionResult Delete(String id = "")
{
    EmployeeList emp = new EmployeeList();
    List<Employee> objEmp = emp.GetEmployeeList(id).OrderBy(x => x.FirstName).ToList();
    return View(objEmp.FirstOrDefault());
}

[HttpPost]
public ActionResult Delete(Employee Emp)
{
    EmployeeList objEmp = new EmployeeList();
    objEmp.DeleteEmployee(Emp);
    return RedirectToAction("Index");
}


For Model Part

public void DeleteEmployee(Employee employee)
{
    try
    {
        SqlParameter[] MyParams = new SqlParameter[1];
        MyParams[0] = new SqlParameter("@ID", employee.ID);
        SqlHelper.ExecuteNonQuery(AppConstants.getConnectionString(), CommandType.StoredProcedure, "[dbo].[uspDeletetUser]", MyParams);
    }
    catch (SqlException ex)
    {
        throw ex;
    }
}


To get Nationality list

public List<Nationality> GetNationality()
{
    try
    {
        DataTable dt = SqlHelper.ExecuteDataTable(AppConstants.getConnectionString(), CommandType.StoredProcedure, "[dbo].[uspGetNationality]");
        var NationalityList = new List<Nationality>();
        foreach (DataRow row in dt.Rows)
        {
            var obj = new Nationality()
            {
                NationalityID = (string)row["Nationality"],
                Name = (string)row["Nationality"]
            };
            NationalityList.Add(obj);
        }
        return NationalityList;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}


Go to Project properties and select Web section and add Employee/ in the specific page.

Start Page

Start Page


For calendar control add these three files to project script folder.
jquery.ui.datepicker.min
jquery.ui.core.min
DatePickerReady
Now Compile and run the project.