Tuesday 2 June 2015

MVCCRUD


Create ASP.NET MVC application to process employee details using Entity Framework (DataBase First Approach)


1. Create ASP.NET MVC application and select Basic Template


2.  Add Employee controller
  • Right-click on Controllers folder
  • Add
  • Controller
  • Rename controller as Employee
  • Click Add button

      3. Add Entity Data Model to the project

  • Right click on Models folder
  • Add
  • ADO.NET Entity Data Model
  • Rename  as Employee  (File name-Employee.edmx)
  • Click OK

 

Follow the steps in the Entity Data Model Wizard
  • Select "Generate from DataBase"
  • Click Next

Provide Connection information
  • Click "New Connection" button
  • Provide details click OK

  • Check your Web.config for the connection string
<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcCRUD-20150602203258;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcCRUD-20150602203258.mdf" />
    <add name="TestdbEntities" connectionString="metadata=res://*/Models.Employee.csdl|res://*/Models.Employee.ssdl|res://*/Models.Employee.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SAS;initial catalog=Testdb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  • Click Next
  • Select the required tables (In this example using Employee Table)
  • Click Finish
  • Build the project

4. Prepare the action methods in EmployeeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcCRUD.Models;
using System.Data;

namespace MvcCRUD.Controllers
{
    public class EmployeeController : Controller
    {
        TestdbEntities db = new TestdbEntities();

        // Code for Get/List
        public ActionResult Index()
        {
            List<Employee> employeelist = db.Employees.ToList();
            return View(employeelist);
        }
        // code for Get/Create
        public ActionResult Create()
        {
            return View();
        }

        // code for Post/Create
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Employees.Add(employee);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(employee);
            }
            catch
            {
                return View();
            }
        }
        // code for Get/Edit
        public ActionResult Edit(int id)
        {
            Employee employee = db.Employees.SingleOrDefault(x => x.Id == id);
            return View(employee);
        }
        // code for Post/Edit
        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(employee).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(employee);
            }
            catch
            {
                return View();
            }
        }
        // code for Get/Details

        public ActionResult Details(int id)
        {
            Employee employee = db.Employees.SingleOrDefault(x => x.Id == id);

            return View(employee);
        }
        // code for Get/Delete
        public ActionResult Delete(int id)
        {
            Employee employee = db.Employees.SingleOrDefault(x => x.Id == id);
            return View(employee);
        }
        // code for Post/Delete
        [HttpPost]
        public ActionResult Delete(Employee employee)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(employee).State = EntityState.Deleted;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(employee);
            }
            catch
            {
                return View();
            }
        }
    }
}

5. Add views for above action methods by using Scaffold templates to generate the views and 
Modify the content according to the requirement.

6. Go to solution Explorer

 App_Start-->RouteConfig.cs

Change the ControllerName to Employee and action to Index  and Build the application.



Index.cshtml

@model IEnumerable<MvcCRUD.Models.Employee>

<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.HireDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Salary)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ContactNo)
        </th>
        <th>Actions</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Id)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Age)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.HireDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Salary)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ContactNo)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}
</table>

Create.cshtml

@model MvcCRUD.Models.Employee

<h2>Create</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
            @Html.DropDownList("Gender", new List<SelectListItem>
            {
              new SelectListItem { Text ="Male",Value="Male"},
              new SelectListItem { Text = "Female",Value="Female"}
            },"--------Select Gender--------")
            @Html.ValidationMessageFor(model => model.Gender)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.HireDate)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(m => m.HireDate, "{0:MM/dd/yyyy}", new { @class="datepicker" })
            @Html.ValidationMessageFor(model => model.HireDate)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Salary)
            @Html.ValidationMessageFor(model => model.Salary)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNo)
            @Html.ValidationMessageFor(model => model.ContactNo)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

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






Edit.cshtml

@model MvcCRUD.Models.Employee

<h2>Edit</h2>
<hr />
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Id)
        </div>
        <div class="editor-field">
           @Html.TextBoxFor(m=>m.Id,new  { disabled = "disabled", @readonly = "readonly" })
            @Html.ValidationMessageFor(model => model.Id)
        </div>

        @Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Gender)
            @Html.ValidationMessageFor(model => model.Gender)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Age)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.HireDate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.HireDate)
            @Html.ValidationMessageFor(model => model.HireDate)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Salary)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Salary)
            @Html.ValidationMessageFor(model => model.Salary)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ContactNo)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ContactNo)
            @Html.ValidationMessageFor(model => model.ContactNo)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

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



Details.cshtml

@model MvcCRUD.Models.Employee

<h2>Details</h2>
<hr />>
<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Name)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Age)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Age)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.HireDate)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.HireDate)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Salary)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Salary)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.ContactNo)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.ContactNo)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>



Delete.cshtml

@model MvcCRUD.Models.Employee

<h2>Delete</h2>
<hr />
<h3>Are you sure you want to delete this?</h3>
<fieldset>
    <legend>Employee</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Name)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Gender)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Gender)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Age)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Age)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.HireDate)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.HireDate)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Salary)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Salary)
    </div>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.ContactNo)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.ContactNo)
    </div>
</fieldset>
@using (Html.BeginForm()) {
    <p>
        <input type="submit" value="Delete" /> |
        @Html.ActionLink("Back to List", "Index")
    </p>
}


Employee.cs

namespace MvcCRUD.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    public partial class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public Nullable<int> Age { get; set; }
        [DisplayFormat(DataFormatString = "{0:d-M-yyy}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> HireDate { get; set; }
        public Nullable<decimal> Salary { get; set; }
        public Nullable<long> ContactNo { get; set; }
    }
}

                                                     MyScripts.js

    $(document).ready(function () {
   
        $("table tr:even").css("background-color","lightgray");
        $("table tr:odd").css("background-color", "ash");
        $('.datepicker').datepicker();
    });

Add these Scripts in Layout.cshtml

    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.20.js"></script>
    <script src="~/Scripts/MyJScript.js"></script>