Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

CRUD Operation in ASP.NET MVC and AngularJS

Insert,Update,Delete in AngularJS and ASP.NET MVC 

In this post I will create sample Asp.net MVC 4 application using AngularJS and perform

CRUD (Create, Read, Update and Delete) operations using SPA (Single Page Application).

First create Asp.net MVC 4 application named “AngularMVC” and then simply follow below steps.

1.  Now create a new Employee class in model folder with name as Employee.cs and add below listed properties.

   public class Employee
     {
 
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
     }


2. Now create entity EmployeeContext.cs class in model folder.

  namespace AngularMVC.Models
  {
    public class EmployeeContext : DbContext
    {
        public EmployeeContext() : base("DefaultConnection")
        {
        }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<EmployeeContext>(null);
        }
        public DbSet<Employee> EmployeeData { get; set; }
    }
  }


3. Now let's add following code in HomeController to Retrieve, Insert, Update and delete Employee records.

       // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmployeeContext contextObj = new EmployeeContext()))
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
 
        // Insert/ADD new employee
        public JsonResult Save(Employee data)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var EmployeeList = contextObj.EmployeeData.Add(data);
                contextObj.SaveChanges();
            }
            return null;
 
        }
 
        // Update existing employee
        public JsonResult Update(int id,string name,string email,string address)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id ==  id).FirstOrDefault();
                employeeList.Name = name;
                employeeList.Email = email;
                employeeList.Address = address;
               
                contextObj.SaveChanges();
            }
            return null;
        }
 
        // Delete existing employee
        public JsonResult Delete(int id)
        {
            using (EmployeeContext contextObj = new EmployeeContext())
            {
                var employeeList = contextObj.EmployeeData.Where(x => x.Id == id).FirstOrDefault();
                contextObj.EmployeeData.Remove(employeeList);
                contextObj.SaveChanges();
            }
            return null;
        }
 

4. Change existing connection string or Add database connection in web.config.

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\;Initial Catalog=SampleAngularMVCDb;Integrated Security=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

5. Go to Scripts and create a new folder as EmployeeScripts, under EmployeeScripts folder create 3 new js files as AngApp.js, EmpController.js & EmpService.js.

 

6. Now under shared folder there is view named _Layout.cshtm, add all these scripts files in that shared view.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <script src="~/EmployeeScripts/js/angular.min.js"></script>
        <script src="~/EmployeeScripts/js/AngApp.js"></script>
        <script src="~/EmployeeScripts/js/EmpController.js"></script>
        <script src="~/EmployeeScripts/js/EmpService.js"></script>
    </head>
   <body>
….
</body>
</html>


7. Now let’s create view named Index.cshtml with AngularJS code under folder Home, then add ng-app,ng-controller,ng-model,ng-repeat,ng-click AnularJS directives in this view with required html code.

 @{
    ViewBag.Title = "Home Page";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-app="EmpApp" ng-controller="EmpCntrlr">
   
        <table border="1" cellpadding="10" align="center">
 
            <tr>
                <td colspan="4">
                    <form name="myForm" novalidate>
                        <table>
                            <tr>
                                <td>
                                    <input type="hidden" id="txtid" name="id" ng-model="employeeData.Id" />
                                </td>
                                <td>
                                    Name:
                                    <input type="text" id="txtEmpName" name="name" ng-model="employeeData.Name" />
                                </td>
                                <td>
                                    Email:
                                    <input type="email" id="txtEmpEmail" name="email" ng-model="employeeData.Email" />
                                    <span ng-show="myForm.email.$error.email">Invalid email address.</span>
                                </td>
                                <td>
                                    Address:
                                    <input type="text" id="txtEmpAddress" name="address" ng-model="employeeData.Address" />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3" style="text-align:right">
                                    <button ng-click="myForm.$valid && Save()">Save</button>
                                   
                                </td>
                            </tr>
                        </table>
                    </form>
          </td>
            </tr>
 
            <tr>
                <th>
                   
                </th>
                <th>
                    Name
                </th>
                <th>
                    Email
                </th>
                <th>
                    Address
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Id'">
 
                <td>
                </td>
                <td>
                    <input type="text" id="txtName" ng-model="emp.Name" />
                </td>
                <td>
                    <input type="text" id="txtem" ng-model="emp.Email" />
                </td>
                <td>
                    <input type="text" id="txtadd" ng-model="emp.Address" />
                </td>
                <td>
                    <button ng-click="Delete(emp.Id)">Delete</button>
                </td>
                <td>
                    <button ng-click="Update(emp.Id,emp.Name,emp.Email,emp.Address)">Update</button>
                </td>
            </tr>
        </table>
</div>
 


8. Open AngApp.js and define angular module as below

var app = angular.module("EmpApp", []);

9. Open EmpService.js and define functions for CRUD (insert, update, delete) operations on Employee.

app.service("EmployeeService", function ($http) {
 
    // Get Employee data
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
    // Delete Employee by Id
    this.DeleteEmployee = function (EmpID) {
        var response = $http({
            method: "post",
            url: "Home/Delete",
            params: {
                id: EmpID
            }
        });
        return response;
    }
    // Update Employee
    this.UpdateEmployee = function (Id, Name, Email, Address) {
        var response = $http({
            method: "post",
            url: "Home/Update",
            params: {
                id: Id, name: JSON.stringify(Name), email: JSON.stringify(Email), address: JSON.stringify(Address)
            }
        });
        return response;
    }
});

 

10.  Open EmpController.js and all required functions(i.e clear(),setdefaultdata() etc) with CRUD operations.

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
 
    $scope.employeeData= {
 
        id: 0,
 
        Name: 'nagnath',
 
        Email: 'test@gmail.com',
 
        Address: 'ok'
 
    }
 
    $scope.Save = function () {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify($scope.employeeData),
            url: '/Home/Save',
            success: function (data, status) {
                ClearFields();
                GetAllEmployee();
            },
            error: function (status) { }
        });
    }
 
     // Angular ajax function deletes employee data for selected employee
       $scope.Delete = function (EmpId) {
        debugger;
        var DelEmployee = EmployeeService.DeleteEmployee(EmpId);
        DelEmployee.then(function (empls) {
            ClearFields();
            GetAllEmployee();
        }, function () {
            alert('Employee data not found');
        });
       }
    // Angular ajax function Update employee data for selected employee
       $scope.Update = function (Id,Name,Email,Address) {
           debugger;
           var UpdateEmployeeData = EmployeeService.UpdateEmployee(Id, Name, Email, Address);
           UpdateEmployeeData.then(function (empls) {
               ClearFields();
               GetAllEmployee();
           }, function () {
               alert('Employee data not found');
           });
       }
 
    function ClearFields() {
        $scope.Name = "";
        $scope.Email = "";
        $scope.Address = "";
      
    }
 
});
 

Final Page Look 


ASP.NET MVC with AngularJS

AngularJS with ASP.NET MVC 

I have already shared post on AngularJS with asp.net CRUD operations but in this post I am going to share Basic example that retrieves data from database and display it using AngularJS,Asp.net MVC and Entity framework.

AngularJS

AngularJS is a JavaScript framework open-source client-side web application framework mainly maintained by Google and by a community of individuals and corporations to address many of the challenges encountered in developing single-page applications.

Following are some angular directives I used in this example

ng-app

Declares the root element of an AngularJS application, under which directives can be used to declare bindings and define behavior.

ng-controller

Specifies a JavaScript controller class that evaluates HTML expressions.

ng-repeat

Instantiate an element once per item from a collection.

AngularJS with ASP.NET MVC Example

In layout section I added reference to angularJS controller,service code.

Layout:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="~/Content/js/AngApp.js"></script>
    <script src="~/Content/js/Employee.js"></script>
    <script src="~/Content/js/Service.js"></script>
</head>
<body>
    @RenderBody()
 
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Asp.net MVC View and AngularJS View

 @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
 <div ng-app="EmpApp" ng-controller="EmpCntrlr">
        <table border="1" cellpadding="10" align="center" class="table table-bordered table-striped">
            <tr>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
            </tr>
            <tr ng-repeat="emp in employees|orderBy :'Name'">
 
                <td>
                    {{emp.Id}}
                </td>
                <td>
                    {{emp.Name}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                 {{emp.EmailId}}
                </td>
            </tr>
        </table>        
         </div>

 

Asp.net Entity framework and Model

 

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace AngularMvcApp.Models
{
    public class EmolyeeDbContext : DbContext  {
        public EmolyeeDbContext(): base("DefaultConnection")      { }
   protected override void OnModelCreating(DbModelBuilder modelBuilder)      {         Database.SetInitializer<EmolyeeDbContext>(null);    }
        public DbSet<EmployeeData> EmployeeData { get; set; }
    }
}

 

Asp.net Employee Model

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; 
 
namespace AngularMvcApp.Models
{
public class EmployeeData
    {
        [Key]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }  }
}

 

Asp.net MVC Controller

using AngularMvcApp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AngularMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            return View();
        }
        // GET: All Employees
        public JsonResult GetAllEmployees()
        {
            using (EmolyeeDbContext contextObj = new EmolyeeDbContext())
            {
                var EmployeeList = contextObj.EmployeeData.ToList();
                return Json(EmployeeList, JsonRequestBehavior.AllowGet);
            }
        }
    }
}

 

AngularJS Model

var app = angular.module("EmpApp", []);

AngularJS Controller

app.controller("EmpCntrlr", function ($scope, EmployeeService) {
    GetAllEmployee();
    function GetAllEmployee() {
        debugger;
        var getAllEmployee = EmployeeService.getEmployee();
        getAllEmployee.then(function (empls) {
            $scope.employees = empls.data;
        }, function () {
            alert('Employee data not found');
        });
    }
});

AngularJS Service

app.service("EmployeeService", function ($http) {
    this.getEmployee = function () {
        debugger;
        return $http.get("/Home/GetAllEmployees");
    };
});

धन्यवाद !!!

Data Annotations

Data Annotations

 In Asp.net MVC, we can easily apply validation to web application by using Data Annotation attribute classes to model class. Data Annotation attribute classes are present in System.ComponentModel.DataAnnotations namespace and are available to Asp.net projects like Asp.net web application & website, Asp.net MVC, Web forms and also to Entity framework ORM models.

Data Annotations help us to define the rules to the model classes or properties for data validation and displaying suitable messages to end users.
The idea behind using data annotations is to add constraints metadata to the properties in the view model. This metadata is then picked up by the default binder when

Data Annotation Validator Attributes

DataType – Specify the datatype of a property
DisplayName – specify the display name for a property.
DisplayFormat – specify the display format for a property like different format for Date property.

The data annotations are listed and described in detail:

1.   EmailAddress: Indicates that the value must be a well-formatted e-mail address.

2.  CreditCard :Defines the value as a credit card number (15 or 16 digits without spaces or dashes).

3.  Required: Specify a property as required.

4.   ReqularExpression  : Validate the value of a property by specified regular expression pattern.

5   Range: Validate the value of a property within a specified range of values.

6.   StringLength : Specify min and max length for a string property.

7.   MaxLength : Specify max length for a string property.

8 .  Bind – Specify fields to include or exclude when adding parameter or form values to model properties.

9.   ScaffoldColumn : Specify fields for hiding from editor forms.

10.  EnumDataType(typeof(name of enum)) :Enables a .NET Framework enumeration to be mapped to a data column.The value must be one of those defined in the enumeration.

11.  FileExtension(Extensions="") : Validates that the file extension of the uploaded file is in the acceptable extensions defined; for example, [FileExtensions(Extensions=".jpg,.png,.gif")].

 

Data annotation Example:

public class Company
    {
        [Key]
        public Int16 CmpId { get; set; }
 
        [Required(ErrorMessage = "Name is required")]
        [StringLength(150)]
        [RegularExpression("^[A-Za-z0-9][A-Za-z0-9_ .-]*", ErrorMessage = "Invalid company name")]
        public string CmpName { get; set; }
 
        [Required(ErrorMessage = "Regestration number is required")]
        [StringLength(150)]
        public string CmpRegestration { get; set; }
 
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        [Required(ErrorMessage = "Registration Date is required")]
        public DateTime CmpRegDate { get; set; }
 
        [Required(ErrorMessage = "Email is required")]
        [DataType(DataType.EmailAddress)]
        [StringLength(150)]
        [RegularExpression(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$")]
        public string CmpEmail { get; set; }
 
 
        public Guid CreatedBy { get; set; }
 
        [ForeignKey("CreatedBy")]
        public aspnet_Users User { get; set; }
 
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime? CreatedDate { get; set; }
 
    }
 



 Custom Data Annotations:

You can create your own custom validations by creating custom data annotations.To create a custom annotation, you need to create a class that inherits from ValidationAttribute, and the name of that class must end with the suffix Attribute.

For example leave application has “from date” and “To date”, now you have to apply custom validation that to date should be always greater than from date.

Following example compares date, if to date is less than from Date then custom data annotation create error message.

Example:

#region Date compare Rule

    public sealed class IsDateAfter : ValidationAttribute
    {
        private readonly string testedPropertyName;
        private readonly bool allowEqualDates;
 
        public IsDateAfter(string testedPropertyName, bool allowEqualDates = false)
        {
            this.testedPropertyName = testedPropertyName;
            this.allowEqualDates = allowEqualDates;
        }
 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var propertyTestedInfo = validationContext.ObjectType.GetProperty(this.testedPropertyName);
            if (propertyTestedInfo == null)
            {
                return new ValidationResult(string.Format("unknown property {0}", this.testedPropertyName));
            }
 
            var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);
 
            if (value == null || !(value is DateTime))
            {
                return ValidationResult.Success;
            }
 
            if (propertyTestedValue == null || !(propertyTestedValue is DateTime))
            {
                return ValidationResult.Success;
            }
 
            // Compare values
            if ((DateTime)value >= (DateTime)propertyTestedValue)
            {
                if (this.allowEqualDates)
                {
                    return ValidationResult.Success;
                }
                if ((DateTime)value > (DateTime)propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
            }
 
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }
 
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessageString,
                ValidationType = "isdateafter"
            };
            rule.ValidationParameters["propertytested"] = this.testedPropertyName;
            rule.ValidationParameters["allowequaldates"] = this.allowEqualDates;
            yield return rule;
        }
    }

    #endregion

 

Use of custom validation:

   public class Leave
    {
        [Key]
        public int LeaveId { get; set; }
 
        public BlogProj.Models.Enum.LeaveCatogry LeaveCatogry { get; set; }
 
        [Display(Name = "From")]
        public DateTime? FromDate { get; set; }
 
        [Display(Name = "To")]
        [IsDateAfter("FromDate", true,ErrorMessage="To date should be after from date")]
        public DateTime? ToDate { get; set; }
  }