Skip to content

Instantly share code, notes, and snippets.

@itorian
Last active December 3, 2015 10:58
Show Gist options
  • Save itorian/7844f3e8c2168ff2142f to your computer and use it in GitHub Desktop.
Save itorian/7844f3e8c2168ff2142f to your computer and use it in GitHub Desktop.
AngularJS CRUD in MVC Sample Demo
Step 1. Install AngularJS using install-package angularjs or using NuGet Package Manager
Step 2. Insert JS code references on web page or _Layout.cshtml page
<script src="~/Scripts/jquery-1.11.1.min.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/AngularImp/EnquiryService.js"></script>
<script src="~/Scripts/AngularImp/EnquiryCtrl.js"></script>
Step 3. Create View Page as given below
<div ng-app="EnquiryList" ng-controller="EnquiryCtrl">
<h2>Enquiry Details</h2>
<form>
<div class="col-sm-12">
<div><input type="hidden" ng-model="c.Id" /></div>
<div class="col-sm-3"><input type="text" placeholder="Name" class="form-control" ng-model="c.Name" id="name" /></div>
<div class="col-sm-3"><input type="text" placeholder="Email" class="form-control" ng-model="c.Email" /></div>
<div class="col-sm-3"><input type="text" placeholder="Contact" class="form-control" ng-model="c.Contact" /></div>
<div class="col-sm-3"><input type="text" placeholder="Details" class="form-control" ng-model="c.Details" /></div>
<div class="col-sm-3">
<input type="submit" value="Save" class="btn btn-primary" ng-click="addEnquiry(c);" ng-hide="IsInEditMode" />
<input type="submit" value="Edit" class="btn btn-primary" ng-click="editEnquiry(c);" ng-show="IsInEditMode" /><input type="button" value="Cancel" class="btn btn-default" ng-click="clearFields();" />
</div>
</div>
</form><br />
<div ng-show="haveEnquiries();">
<h2>Enquiry List</h2>
<hr />
<table class="table table-striped">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Email</td>
<td>Contact</td>
<td>Details</td>
<td></td>
</tr>
</thead>
<tbody>
<tr ng-repeat="enquiry in enquiries">
<td>{{enquiry.Id}}</td>
<td>{{enquiry.Name}}</td>
<td>{{enquiry.Email}}</td>
<td>{{enquiry.Contact}}</td>
<td>{{enquiry.Details}}</td>
<td>
<button type="button" class="btn btn-primary btn-xs" ng-click="doEdit(enquiry);">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Edit
</button>
<button type="button" class="btn btn-danger btn-xs" ng-click="deleteEnquiry(enquiry.Id);">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
Step 4. Create code first DbContext like below
public partial class FreshMachli : DbContext
{
public FreshMachli()
: base("name=FreshMachli")
{
}
public virtual DbSet<FreshMachliEnquiry> FreshMachliEnquiries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
public partial class FreshMachliEnquiry
{
public int Id { get; set; }
[StringLength(50)]
public string Name { get; set; }
[StringLength(50)]
public string Email { get; set; }
[StringLength(50)]
public string Contact { get; set; }
public string Details { get; set; }
}
Step 5. Create Repository like below which is using above DbContext
public class EnquiryRepository
{
private FreshMachli _context;
public EnquiryRepository()
{
_context = new FreshMachli();
}
public bool CreateEnquiry(FreshMachliEnquiry model)
{
_context.FreshMachliEnquiries.Add(model);
return (_context.SaveChanges() > 0);
}
public List<FreshMachliEnquiry> GetAllEnquiries()
{
return _context.FreshMachliEnquiries.ToList();
}
public FreshMachliEnquiry GetEnquiryById(int Id)
{
return _context.FreshMachliEnquiries.Where(u => u.Id == Id).SingleOrDefault();
}
public bool UpdateEnquiry(FreshMachliEnquiry usr)
{
FreshMachliEnquiry enquiryToUpdate = _context.FreshMachliEnquiries.Where(u => u.Id == usr.Id).SingleOrDefault();
enquiryToUpdate.Name = usr.Name;
enquiryToUpdate.Email = usr.Email;
enquiryToUpdate.Contact = usr.Contact;
enquiryToUpdate.Details = usr.Details;
_context.Entry(enquiryToUpdate).State = System.Data.Entity.EntityState.Modified;
return (_context.SaveChanges() > 0);
}
public bool DeleteEnquiry(int Id)
{
try
{
FreshMachliEnquiry ItemToDelete = _context.FreshMachliEnquiries.Where(u => u.Id == Id).SingleOrDefault();
_context.Entry(ItemToDelete).State = System.Data.Entity.EntityState.Deleted;
return (_context.SaveChanges() > 0);
}
catch (Exception)
{
return false;
}
}
}
Step 6. Now implement following methods inside MVC Controller
EnquiryRepository repo = new EnquiryRepository();
[HttpPost]
public JsonResult CreateEnquiry(FreshMachliEnquiry enquiry)
{
return Json(repo.CreateEnquiry(enquiry));
}
[HttpGet]
public JsonResult GetEnquiries()
{
return Json(repo.GetAllEnquiries(), JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetEnquiry(int id)
{
return Json(repo.GetEnquiryById(id), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult UpdateEnquiry(FreshMachliEnquiry enquiry)
{
return Json(repo.UpdateEnquiry(enquiry));
}
[HttpPost]
public JsonResult DeleteEnquiry(int Id)
{
return Json(repo.DeleteEnquiry(Id), JsonRequestBehavior.AllowGet);
}
Step 7. Now let’s create angularjs service which will call above MVC controllers
// Angular service to handle all remote server interactions
var myEnquiry = angular.module("EnquiryList", []);
myEnquiry.service("Repo", ["$http", function ($http) {
// Add new Enquiry
this.addEnquiry = function (usr) {
var enquiryObj = { "Id": usr.Id, "Name": usr.Name, "Email": usr.Email, "Contact": usr.Contact, "Details": usr.Details }
var config = { method: "POST", url: "/Home/CreateEnquiry", data: enquiryObj };
return $http(config);
};
// Get All Enquiries
this.GetEnquiries = function () {
return $http.get("/Home/GetEnquiries");
};
// Get Single Enquiry
this.GetEnquiry = function (id) {
var config = { method: "GET", url: "/Home/GetEnquiry", data: Id };
$http(config)
.success(function (data, status, header, config) {
alert(data);
}).error(function (data, status, header, config) {
alert("Error: Something went wrong");
});
};
// Edit Enquiry
this.editEnquiry = function (usr) {
var enquiryObj = { "Id": usr.Id, "Name": usr.Name, "Email": usr.Email, "Contact": usr.Contact, "Details": usr.Details };
var config = { method: "POST", url: "/Home/UpdateEnquiry", data: enquiryObj };
return $http(config);
};
// Delete Enquiry
this.deleteEnquiry = function (id) {
var enquiryObj = { "Id": id };
var config = { method: "POST", url: "/Home/DeleteEnquiry", data: enquiryObj };
return $http(config);
};
}]);
Step 8. Now let’s use above angular repository in angular controller
// Controller is update with the custome Repo and window service dependancy
myEnquiry.controller("EnquiryCtrl", ["$scope", "$window", "Repo", function ($scope, $window, $Repo) {
$scope.enquiries = [];
$scope.c = { Id: "", Name: "", Email: "", Contact: "", Details: "" };
$scope.IsInEditMode = false;
clearFields = function () {
$scope.c.Id = "";
$scope.c.Name = "";
$scope.c.Email = "";
$scope.c.Contact = "";
$scope.c.Details = "";
$scope.IsInEditMode = false;
};
$scope.clearFields = clearFields;
addEnquiry = function (enquiry) {
$Repo.addEnquiry(enquiry)
.success(function (data, status, header, config) {
getEnquiries();
clearFields();
$scope.isEditMode = false;
$("#name").focus();
})
.error(function (data, status, header, config) {
alert("Error: Something went wrong");
});
};
$scope.addEnquiry = addEnquiry;
doEdit = function (enquiry) {
var localCopy = angular.copy(enquiry);
$scope.c.Id = localCopy.Id;
$scope.c.Name = localCopy.Name;
$scope.c.Email = localCopy.Email;
$scope.c.Contact = localCopy.Contact;
$scope.c.Details = localCopy.Details;
$scope.IsInEditMode = true;
}
$scope.doEdit = doEdit;
getEnquiries = function () {
$Repo.GetEnquiries()
.success(function (data, status, header, config) {
$scope.enquiries = data;
})
.error(function (data, status, header, config) {
alert("Error: Something went wrong");
})
};
editEnquiry = function (xEnquiry) {
$Repo.editEnquiry(xEnquiry).success(function (data, status, header, config) {
getEnquiries();
clearFields();
$scope.isEditMode = false;
})
.error(function (data, status, header, config) {
alert("Error: Something went wrong");
});
}
$scope.editEnquiry = editEnquiry;
deleteEnquiry = function (Id) {
if ($window.confirm("Are you sure you want to delete the enquiry")) {
$Repo.deleteEnquiry(Id).success(function (data, status, header, config) {
getEnquiries();
clearFields();
$scope.isEditMode = false;
}).error(function (data, status, header, config) {
alert("Error: Something went wrong");
});
}
}
$scope.deleteEnquiry = deleteEnquiry;
haveEnquiries = function () {
return $scope.enquiries.length > 0 ? true : false;
}
$scope.haveEnquiries = haveEnquiries;
clearFields();
getEnquiries();
}]);
Now run the application.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment