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.