CRUD operations using Asp.Net MVC End to end Sample
First We create a Aps.Net MVC web application
After add a Controller => SampleController.cs
Add below code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using crudMVC.Models;
namespace crudMVC.Controllers
{
public class SampleController : Controller
{
EmployeeEntities employeeEntities = new EmployeeEntities();
// GET: Sample
public ActionResult Index()
{
return View(employeeEntities.Employees.ToList());
}
[HttpGet]
public ActionResult GetById(int id)
{
return View(employeeEntities.Employees.FirstOrDefault(a => a.eno == id));
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
Employee employees = employeeEntities.Employees.FirstOrDefault(a => a.eno == employee.eno);
if (employees != null)
{
employees.ename = employee.ename;
employees.salary = employee.salary;
employeeEntities.Entry(employees).State = EntityState.Modified;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
else
{
employeeEntities.Employees.Add(employee);
employeeEntities.Entry(employee).State = EntityState.Added;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
}
else
{
return RedirectToAction("Index");
}
}
[HttpGet]
public ActionResult Edit(int id)
{
return View(employeeEntities.Employees.FirstOrDefault(a => a.eno == id));
}
[HttpPost]
public ActionResult Edit(Employee employee)
{
if (ModelState.IsValid)
{
Employee employees = employeeEntities.Employees.FirstOrDefault(a => a.eno == employee.eno);
if (employees != null)
{
employees.ename = employee.ename;
employees.salary = employee.salary;
employeeEntities.Entry(employees).State = EntityState.Modified;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
else
{
employeeEntities.Employees.Add(employee);
employeeEntities.Entry(employee).State = EntityState.Added;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
}
else
{
return RedirectToAction("Index");
}
}
[HttpGet]
public ActionResult Delete(int id)
{
return View(employeeEntities.Employees.FirstOrDefault(a => a.eno == id));
}
[HttpPost]
public ActionResult Delete(string id)
{
int ids = 0;
int.TryParse(id, out ids);
Employee employees = employeeEntities.Employees.FirstOrDefault(a => a.eno == ids);
if (employees != null)
{
employeeEntities.Employees.Remove(employees);
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
}
}
IN WebApiconfig and add this below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace crudMVC
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
After add a Controller => SampleController.cs
Add below code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using crudMVC.Models;
namespace crudMVC.Controllers
{
public class SampleController : Controller
{
EmployeeEntities employeeEntities = new EmployeeEntities();
// GET: Sample
public ActionResult Index()
{
return View(employeeEntities.Employees.ToList());
}
[HttpGet]
public ActionResult GetById(int id)
{
return View(employeeEntities.Employees.FirstOrDefault(a => a.eno == id));
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
Employee employees = employeeEntities.Employees.FirstOrDefault(a => a.eno == employee.eno);
if (employees != null)
{
employees.ename = employee.ename;
employees.salary = employee.salary;
employeeEntities.Entry(employees).State = EntityState.Modified;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
else
{
employeeEntities.Employees.Add(employee);
employeeEntities.Entry(employee).State = EntityState.Added;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
}
else
{
return RedirectToAction("Index");
}
}
[HttpGet]
public ActionResult Edit(int id)
{
return View(employeeEntities.Employees.FirstOrDefault(a => a.eno == id));
}
[HttpPost]
public ActionResult Edit(Employee employee)
{
if (ModelState.IsValid)
{
Employee employees = employeeEntities.Employees.FirstOrDefault(a => a.eno == employee.eno);
if (employees != null)
{
employees.ename = employee.ename;
employees.salary = employee.salary;
employeeEntities.Entry(employees).State = EntityState.Modified;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
else
{
employeeEntities.Employees.Add(employee);
employeeEntities.Entry(employee).State = EntityState.Added;
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
}
else
{
return RedirectToAction("Index");
}
}
[HttpGet]
public ActionResult Delete(int id)
{
return View(employeeEntities.Employees.FirstOrDefault(a => a.eno == id));
}
[HttpPost]
public ActionResult Delete(string id)
{
int ids = 0;
int.TryParse(id, out ids);
Employee employees = employeeEntities.Employees.FirstOrDefault(a => a.eno == ids);
if (employees != null)
{
employeeEntities.Employees.Remove(employees);
employeeEntities.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
}
}
IN WebApiconfig and add this below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace crudMVC
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Solution explorer And add Models
Model folder right click Add Data submenu Aspnet Data model
Give connection string and select Related tables
click on ok
The below Two classes like Context and Entity Class
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class EmployeeEntities : DbContext
{
public EmployeeEntities()
: base("name=EmployeeEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
}
using System;
using System.Collections.Generic;
public partial class Employee
{
public int eno { get; set; }
public string ename { get; set; }
public Nullable<int> salary { get; set; }
}
Add views in MVC controller:
Index.cshtml:
@model IEnumerable<crudMVC.Models.Employee>
@{
ViewBag.Title = "All Employees";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
@*<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>*@
<link href="~/Content/bootstrap/bootstrap.css" rel="stylesheet" />
@*<link href="~/Content/bootstrap/bootstrap.min.css" rel="stylesheet" />*@
@*<script src="~/Scripts/bootbox.min.js"></script>
<script src="~/Scripts/bootbox.js"></script>*@
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(':checkbox').on('change', function () {
var th = $(this), name = th.prop('name');
if (th.is(':checked')) {
$(':checkbox[name="' + name + '"]').not($(this)).prop('checked', false);
}
});
});
function edit() {
debugger;
var values = $('input:checked').map(function () {
return this.value;
}).get();
location.href = '@Url.Action("Edit", "Sample")/' + values;
};
function details() {
debugger;
var values = $('input:checked').map(function () {
return this.value;
}).get();
var samples = values.indexOf();
if (samples != -1)
location.href = '@Url.Action("GetById", "Sample")/' + values;
else {
alert('Please select at least one Employee!');
debugger;
}
alert("Please select at least one Employee!");
};
</script>
@*<style type="text/css">
#rcorners2 {
border-radius: 25px;
border: 2px solid #73AD21;
padding: 20px;
}
.modal {
/* display: block;*/
padding-right: 0px;
background-color: rgba(4, 4, 4, 0.8);
}
.modal-dialog {
top: 50%;
/*width: 100%;
position: absolute;*/
}
.modal-content {
border-radius: 0px;
border: none;
top: 40%;
}
.modal-body {
background-color: #0f8845;
color: white;
}
</style>*@
@*height: 150px;*@
@*<div id="myModal" class="modal hide fade">
<!-- dialog contents -->
<div class="modal-body">Hello world!</div>
<!-- dialog buttons -->
<div class="modal-footer"><a href="#" class="btn primary">OK</a></div>
</div>*@
<h2>Employee Management</h2>
<div>
@Html.ActionLink("Create New", "Create")
<button class="btn btn-default" style="float: right;" title="Details" onclick="details()"><span class="glyphicon glyphicon-eye-open"></span></button>
<button class="btn btn-default" style="float: right;" title="Edit" onclick="edit()"><span class="glyphicon glyphicon-edit"></span></button>
<button class="btn btn-default" style="float: right;" title="Create" onclick="location.href='@Url.Action("Create", "Sample")'"><span class="glyphicon glyphicon-plus"></span></button>
</div>
<table class="table" border="1">
<tr>
<th width="5px">
</th>
<th>
Employee Name @*@Html.DisplayNameFor(model => model.ename)*@
</th>
<th>
Salary @*@Html.DisplayNameFor(model => model.salary)*@
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="checkboxdata" id="check" value="@item.eno" class="myCheckbox" />
</td>
<td>
@Html.DisplayFor(modelItem => item.ename)
</td>
<td>
@Html.DisplayFor(modelItem => item.salary)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.eno }) |
@Html.ActionLink("Details", "GetById", new { id = item.eno }) |
@Html.ActionLink("Delete", "Delete", new { id = item.eno })
</td>
</tr>
}
</table>
@*<div class="container">
<div class="row">
<h2>Windows 8 Bootstrap Modals </h2>
</div>
<div class="row">
<!-- Large modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Custome model pop up!</button>
<div class="modal fade bs-example-modal-lg" role="dialog" aria-labelledby="myLargeModalLabel">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<H2>Please !</H2>
@*<h4>Your Laptop battery is less then 10%.Recharge the battery.</h4>
</div>
</div>
</div>
</div>
</div>
</div>*@
GetBYId.cshtml
@model crudMVC.Models.Employee
@{
ViewBag.Title = "GetById";
}
<h4>Employee @Html.DisplayFor(model => model.ename) Details</h4>
<div>
<hr />
<dl class="dl-horizontal">
@*<dt>
@Html.DisplayNameFor(model => model.salary)
</dt>*@
<dd>
<b>Salary :</b> @Html.DisplayFor(model => model.salary)   @Html.ActionLink("Edit", "Edit", new { id = Model.eno }) |
  <a href="~/Sample/Index" class="btn btn-group">Back to All Employees</a>
</dd>
</dl>
</div>
@*<p>
</p>*@
Edit.cshtml:
@model crudMVC.Models.Employee
@{
ViewBag.Title = "Edit";
}
<h2>Employee Details Editing</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.eno)
<div class="form-group">
@Html.Label("Employee Name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ename, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ename, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.Label("Salary", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.salary, "", 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"/>
  <a href="~/Sample/Index" class="btn btn-group">Back to All Employees</a>
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Delete.cshtml:
@model crudMVC.Models.Employee
@{
ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h4>Employee Deletion</h4>
<div>
<h3>Are you sure you want to delete this?</h3>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayName("Employee Name")
</dt>
<dd>
@Html.DisplayFor(model => model.ename)
</dd>
<dt>
@Html.DisplayName("Salary")
</dt>
<dd>
@Html.DisplayFor(model => model.salary)
</dd>
</dl>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-actions no-color">
<input type="submit" value="Delete" class="btn btn-default" /> |
  <a href="~/Sample/Index" class="btn btn-group">Back to All Employees</a>
</div>
}
</div>
Create.cshtml:
@model crudMVC.Models.Employee
@{
ViewBag.Title = "Create";
}
<h2>Employee Creation</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.Label("Employee Number", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.eno, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.eno, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.Label("Employee Name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ename, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ename, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.Label("Salary", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.salary, "", 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" />
  <a href="~/Sample/Index" class="btn btn-group">Back to All Employees</a>
</div>
</div>
</div>
}
@*<div>
</div>*@
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
in web.config file:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-crudMVC-20160912065030.mdf;Initial Catalog=aspnet-crudMVC-20160912065030;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="EmployeeEntities" connectionString="metadata=res://*/Models.my.csdl|res://*/Models.my.ssdl|res://*/Models.my.msl;provider=System.Data.SqlClient;provider connection string="data source=WINCTRL-SBORA89\SQLEXPRESS;initial catalog=Employee;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Comments
Post a Comment