Today, we will create an ASP.NET MVC 4 application using AngularJS and perform CRUD (Create, Read, Update, and Delete) operations and Multi-Row Insert using Web API.
Background
The basic idea behind it is that some time ago, I was trying to search multi-row insert demos in MVC with Angular, using Web API but did not find any good solution. Then, I decided to write about this from a basic level. We all know that AngularJS is the most popular MVW (Model View Whatever) JavaScript framework for single page application development and believe that it's fun to develop applications on it.
Getting Started
- Start Visual Studio 2012 or later.
- Create a new project.
- Select ASP.NET MVC 4 Web Application.
- Provide the name of the project as demoAngular.
- Set the location where you want to save the project.
- Click on OK button.
- Now, select the project template "Empty" or "Basic"; and the View engine will be razor.
- Click on OK button.
After that, your application looks like this (note : expect AngularController).
The next step is to add new Model class in the Models directory. And, name it as StudentData.cs.
- namespace demoAngular.Models
- {
- public class StudentData
- {
- public int KeyId { get; set; }
- public string SName { get; set; }
- public string FName { get; set; }
- public string Gender { get; set; }
- public string MobileNo { get; set; }
- public int StateId { get; set; }
- public int CityID { get; set; }
- public int ProcID { get; set; }
- public string SXML { get; set; }
- public IEnumerable<StudentData> StudentDataList { get; set; }
- public List<ClassModel> ClassList { get; set; }
- }
-
- public class StateMaster
- {
- public int StateId { get; set; }
- public string StateName { get; set; }
- public IEnumerable<StateMaster> StateMasterList { get; set; }
- }
-
- public class CityMaster
- {
- public int CityID { get; set; }
- public string CityName { get; set; }
- public int StateId { get; set; }
- public IEnumerable<CityMaster> CityMasterList { get; set; }
- }
- public class ClassModel
- {
- public int StudentID { get; set; }
- public string ClassName { get; set; }
- public string BoardName { get; set; }
- public string CRollNo { get; set; }
- public int MM { get; set; }
- public int OM { get; set; }
- public int Divi { get; set; }
- public List<ClassModel> ClassList { get; set; }
- }
- }
After adding the StudentData.cs, add one model.cs file and give the name as DataLayer.cs.
Namespaces
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Data.SqlClient;
- namespace demoAngular.Models
- {
- public class DataLayer : DbContext
- {
- public virtual IEnumerable<StudentData> StudentSubmiteDetails(StudentData Model)
- {
- var sqlParams = new SqlParameter[]{
- new SqlParameter { ParameterName = "@KeyId",Value=Model.KeyId==null?0:Model.KeyId},
- new SqlParameter { ParameterName = "@SName",Value=Model.SName??string.Empty},
- new SqlParameter { ParameterName = "@FName",Value=Model.FName??string.Empty},
- new SqlParameter { ParameterName = "@Gender", Value = Model.Gender??string.Empty },
- new SqlParameter { ParameterName = "@MobileNo", Value = Model.MobileNo??string.Empty},
- new SqlParameter { ParameterName = "@StateId",Value=Model.StateId==null?0:Model.StateId},
- new SqlParameter { ParameterName = "@CityID",Value=Model.CityID==null?0:Model.CityID},
- new SqlParameter { ParameterName = "@ProcID", Value = Model.ProcID},
- new SqlParameter { ParameterName = "@XML", Value = Model.SXML}
- };
- var sqlQaury = @"PROC_StudentSubmitDetails @KeyId, @SName,@FName,@Gender,@MobileNo,@StateId,@CityID,@ProcID,@XML";
- var IList = this.Database.SqlQuery<StudentData>(sqlQaury, sqlParams);
- return IList;
- }
-
- public IEnumerable<StudentData> StudentALLDetails(int ProcID, int Keyid)
- {
- var sqlParams = new SqlParameter[]{
- new SqlParameter { ParameterName = "@ProcID", Value = ProcID},
- new SqlParameter { ParameterName = "@Keyid", Value = Keyid}};
- var sqlQaury = @"PROC_StudentALLDetails @ProcID,@Keyid";
- var IList = this.Database.SqlQuery<StudentData>(sqlQaury, sqlParams);
- return IList;
- }
- public IEnumerable<StudentData> StudentOneDetails(int ProcID, int Keyid)
- {
- var sqlParams = new SqlParameter[]{
- new SqlParameter { ParameterName = "@ProcID", Value = ProcID},
- new SqlParameter { ParameterName = "@Keyid", Value = Keyid}};
- var sqlQaury = @"PROC_StudentALLDetails @ProcID,@Keyid";
- var IList = this.Database.SqlQuery<StudentData>(sqlQaury, sqlParams);
- return IList;
- }
-
- public IEnumerable<ClassModel> StudenteduDetails(int ProcID, int Keyid)
- {
- var sqlParams = new SqlParameter[]{
- new SqlParameter { ParameterName = "@ProcID", Value = ProcID},
- new SqlParameter { ParameterName = "@Keyid", Value = Keyid}};
- var sqlQaury = @"PROC_StudentALLDetails @ProcID,@Keyid";
- var IList = this.Database.SqlQuery<ClassModel>(sqlQaury, sqlParams);
- return IList;
- }
-
- public IEnumerable<StateMaster> BindLstate(int Procid)
- {
- var sqlParms = new SqlParameter[]{
-
- new SqlParameter{ParameterName="@Procid",Value=Procid},};
- var sqlqaury = @"Proc_getState @Procid";
- var IList = this.Database.SqlQuery<StateMaster>(sqlqaury, sqlParms);
- return IList;
- }
-
- public IEnumerable<CityMaster> BindLcity(int Pracid, int stateid)
- {
- var sqlParms = new SqlParameter[]{
- new SqlParameter{ParameterName="@Procid",Value=Pracid},
- new SqlParameter{ParameterName="@Stateid",Value=stateid}};
- var sqlQaury = @"Proc_getState @Procid,@Stateid";
- var IList = this.Database.SqlQuery<CityMaster>(sqlQaury, sqlParms);
- return IList;
- }
-
- public IEnumerable<StudentData> DeleteStudentbyid(int ProcID, int Keyid)
- {
- var sqlParams = new SqlParameter[]{
- new SqlParameter { ParameterName = "@ProcID", Value = ProcID},
- new SqlParameter { ParameterName = "@Keyid", Value = Keyid}};
- var sqlQaury = @"PROC_StudentALLDetails @ProcID,@Keyid";
- var IList = this.Database.SqlQuery<StudentData>(sqlQaury, sqlParams);
- return IList;
- }
- }
-
-
- }
After adding Model, your project looks like this,
Now, add Controller to the Controllers directory and give name as HomeController,
- namespace demoAngular.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult StudentRecord()
- {
- return PartialView("StudentRecord");
- }
- public ActionResult StudentView()
- {
- return PartialView("StudentView");
- }
- }
- }
Now, add another Controller to and give name as ValueController,
Namespaces
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Xml.Linq;
- using demoAngular.Models;
- using Newtonsoft.Json;
- namespace demoAngular.Controllers
- {
- public class ValuesController : ApiController
- {
- DataLayer db = new DataLayer();
- [HttpPost]
- [ActionName("AddNewStudent")]
- public StudentData AddnewStudent(StudentData Model)
- {
- Model.ProcID = 1;
- List<ClassModel> valueSet = Model.ClassList;
- XElement root = new XElement("root");
- for (int i = 0; i < valueSet.Count; i++)
- {
- XElement ele = new XElement("Student", new XElement("ClassName", valueSet[i].ClassName),
- new XElement("BoardName", valueSet[i].BoardName),
- new XElement("CRollNo", valueSet[i].CRollNo),
- new XElement("MM", valueSet[i].MM),
- new XElement("OM", valueSet[i].OM),
- new XElement("Divi", valueSet[i].Divi));
- root.Add(ele);
- }
- XElement xmlclass = root;
- Model.SXML = xmlclass.ToString();
- var mod = db.StudentSubmiteDetails(Model).ToList();
- return mod.FirstOrDefault();
- }
-
- [HttpGet]
- [ActionName("ShowALLStudent")]
- public IEnumerable<StudentData> ShowALLStudent()
- {
- var mod = db.StudentALLDetails(2,0).ToList();
- return mod;
- }
-
- [HttpGet]
- [ActionName("ShowOneStudent")]
- public IEnumerable<StudentData> ShowOneStudent(int id)
- {
- var mod = db.StudentOneDetails(3, id).ToList();
- return mod;
- }
-
- [HttpGet]
- [ActionName("ShowEduStudent")]
- public IEnumerable<ClassModel> ShowEduStudent(int id)
- {
- ClassModel mod1 = new ClassModel();
- mod1.ClassList = db.StudenteduDetails(4, id).ToList();
- return mod1.ClassList;
- }
-
- [HttpGet]
- [ActionName("ShowState")]
- public IEnumerable<StateMaster> ShowState()
- {
- var mod = db.BindLstate(1).ToList();
- return mod;
- }
-
- [HttpGet]
- [ActionName("ShowCity")]
- public IEnumerable<CityMaster> ShowCity(int id)
- {
- var mod = db.BindLcity(2,id).ToList();
- return mod;
- }
-
- [HttpDelete]
- [ActionName("DeleteStudent")]
- public IEnumerable<StudentData> DeleteStudent(int id)
- {
- var mod = db.DeleteStudentbyid(5, id).ToList();
- return mod;
- }
- }
- }
After adding Controller, your project looks like this.
Now, add AngularJS using Manage Nuget Package Manager and search AngularJS. And install it (it’s already instaledl in my project that's why it is showing uninstall)
Now, add a new folder, give name as AngularController, and add JavaScript file in the AngularController directory and add Angular functions.
RohitService.js
- app.service("RohitService", function ($http) {
-
- this.AddNewStudent = function (Student) {
- var request = $http({
- method: "post",
- url: "/api/Values/AddNewStudent",
- data: Student
- });
- return request;
- };
-
- this.ShowStudent = function () {
- var request = $http({
- method: "get",
- url: "/api/Values/ShowALLStudent",
- cache: false,
- async: false
- });
- return request;
- };
-
- this.showStudentone = function (id) {
- var request = $http({
- method: "get",
- url: "/api/Values/ShowOneStudent/" + id,
- cache: false,
- async: false
- });
- return request;
- }
-
- this.showEduStudent = function (id) {
- var request = $http({
- method: "get",
- url: "/api/Values/ShowEduStudent/" + id,
- cache: false,
- async: false
- });
- return request;
- }
-
- this.getState = function () {
- var request = $http({
- method: "get",
- url: "/api/Values/ShowState",
-
- cache: false,
- async: false
- });
- return request;
- };
-
- this.getCity = function (id) {
- var request = $http({
- method: "get",
- url: "/api/Values/ShowCity/" + id,
- cache: false,
- async: false
- });
- return request;
- }
-
- this.deleteStudentKey = function (id) {
- var request = $http({
- method: "delete",
- url: "/api/Values/DeleteStudent/" + id,
- cache: false,
- async: false
- });
- return request;
- }
- });
StudentRecordcontroller.js (it is angular controller)
- app.controller("StudentRecordcontroller", function ($scope, RohitService, $location, ShareData) {
- $scope.val = "Submit";
- loadStateName();
- loadStudentRecord();
- if (ShareData.KeyId == "0") {
- resetForm();
- }
- $scope.finalSubmit = function () {
- var Student = {
- KeyId: $scope.KeyId,
- SName: $scope.SName,
- FName: $scope.FName,
- Gender: $scope.Gender,
- MobileNo: $scope.MobileNo,
- StateId: $scope.StateId.StateId,
- CityID: $scope.CityID.CityID,
- ClassList: $scope.ClassModel
- };
- var promisePost = RohitService.AddNewStudent(Student);
- promisePost.then(function (pl) {
- var student = pl.data;
- if ($scope.val == "Submit") {
- alert('your record save successfully');
- }
- else {
- alert('your record update successfully');
- $scope.val = "Submit";
- }
- resetForm();
- },
- function (errorPl) {
- alert('Error In Request ,Try Again Later');
- })
- };
- $scope.restSubmit = function () {
- resetForm();
- };
- function resetForm() {
- $scope.SName = null;
- $scope.FName = null;
- $scope.Gender= null;
- $scope.MobileNo = null;
- $scope.StateId = null;
- $scope.CityID = null;
- $scope.ClassModel = [{ Index: "0", "ClassName": "", "BoardName": "", "CRollNo": "", "MM": "", "OM": "", "Divi": "" }];
- $scope.val = "Submit";
- }
- function loadStudentRecord() {
- var KeyId=ShareData.KeyId;
- var promiseStudentRecord = RohitService.showStudentone(KeyId);
- promiseStudentRecord.then(function (pl) {
- var values=''
- var stud = pl.data;
- $scope.KeyId = stud[0].KeyId,
- $scope.SName = stud[0].SName,
- $scope.FName = stud[0].FName,
- $scope.Gender = stud[0].Gender,
- $scope.MobileNo = stud[0].MobileNo,
- $scope.StateId = { "StateId": stud[0].StateId };
- StateNameChange();
- $scope.CityID = { "CityID": stud[0].CityID };
- loadEduRecord(stud[0].KeyId);
- $scope.val = "Update";
- ShareData.KeyId = "0";
- },
- function (errorPl) {
- $scope.error = errorPl;
- });
- }
- function loadEduRecord(id) {
- var promiseStudentRecord = RohitService.showEduStudent(id);
- promiseStudentRecord.then(function (pl) {
- var stud = pl.data;
- $scope.ClassModel = stud;
- },
- function (errorPl) {
- $scope.error = errorPl;
- });
- }
-
- function loadStateName() {
- var promiseStateName = RohitService.getState();
- promiseStateName.then(function (pl) {
- $scope.States = pl.data
- },
- function (errorPl) {
- $scope.error = errorPl;
- });
- }
-
- $scope.OnStateNameChange = function () {
- StateNameChange();
- }
- function StateNameChange() {
- if (angular.isDefined($scope.StateId.StateId)) {
- var StateNameid = $scope.StateId.StateId;
- var promiseCityName = RohitService.getCity(StateNameid);
- promiseCityName.then(function (pl) {
- $scope.Cities = pl.data
- },
- function (errorPl) {
- $scope.error = errorPl;
- });
- }
- }
-
- $scope.ClassModel = [{ Index: "0", "ClassName": "", "BoardName": "", "CRollNo": "", "MM": "", "OM": "", "Divi": "" }
-
- ];
-
- $scope.add = function () {
- var a = $scope.ClassModel.length;
- $scope.ClassModel.push({
- 'Index':a,
- 'ClassName': "",
- 'BoardName':"",
- 'CRollNo': "",
- 'MM': "",
- 'OM': "",
- 'Divi': ""
- });
- }
-
-
-
-
-
-
- $scope.remove = function (index)
- {
- if (confirm('Are you sure to delete?'))
- {
- var index = -1;
- var comArr = eval($scope.ClassModel);
- for (var i = 0; i < comArr.length; i++)
- {
- if (comArr[i].Index ===Index)
- {
- index = i;
- break;
- }
- }
- }
- if (index === -1)
- {
- alert("Something goes wrong !")
- }
- $scope.ClassModel.splice(index,1)
- }
-
- });
StudentViewController.js
Now, add the View. After adding View, your project looks like this.
Index.cshtml
- <!DOCTYPE html>
- <html data-ng-app="AngularModule">
- <head>
- <script src="~/Scripts/angular.min.js"></script>
- <script src="~/Scripts/angular-route.min.js"></script>
- <link href="~/Content/Styletest.css" rel="stylesheet" />
- <script src="~/AngularController/RohitRoute.js"></script>
- <script src="~/AngularController/RohitService.js"></script>
- <script src="~/AngularController/StudentRecordcontroller.js"></script>
- <script src="~/AngularController/StudentViewcontroller.js"></script>
- </head>
- <body>
- <table style="width: 99%;">
- <tr>
- <td colspan="2" class="Header">
- <center><h1>Angular Test Header</h1></center>
- </td>
- </tr>
- <tr>
- <td class="left">
- <ul>
- <li><a href="#/studentRecord">Application Form</a></li>
- <li><a href="#/studentView">View Form</a></li>
- </ul>
- </td>
- <td class="right">
- <ng-view>
- </ng-view>
- </td>
- </tr>
- <tr>
- <td colspan="2" class="footer">
- <center><h1>Footer</h1></center>
- </td>
- </tr>
- </table>
- </body>
- </html>
StudentRecord.cshtml
StudentView.cshtml
- @{
- ViewBag.Title = "Student View";
- }
- <h2>Student View</h2>
- <table>
- <tr>
- <thead>
-
- <th>Student Name
- </th>
- <th>Father's Name
- </th>
- <th>Gender
- </th>
- <th>Mobile No.
- </th>
- </thead>
- </tr>
- <tr>
- <tbody data-ng-repeat="students in student">
-
- </td>
- <td>{{students.SName | uppercase}}
- </td>
- <td>{{students.FName}}
- </td>
- <td>{{students.Gender}}
- </td>
- <td>{{students.MobileNo}}
- </td>
- <td>
- <span data-ng-click="editEmployee(students.KeyId)">Edit</span>
- <span data-ng-click="deleteEmployee(students.KeyId)">Delete</span>
- </td>
- </tbody>
- </tr>
- </table>
Now, build your project and run it.
After running your application it's here .