Skip to main content

Featured post

XM Cloud content sync from prod to uat or UAT to prod step by step

When working with Sitecore, it’s common to need content synchronization across environments. Today, I’ll walk you through the steps to sync content from Production to UAT/TEST and vice versa. Steps to Follow 1. Set Up Your Workspace Create a folder on your computer where you will manage the script files and exported data. Open the folder path in PowerShell to begin scripting. We need to run some scripts in PowerShell to update the folder with the basic requirements for syncing content. PS C:\Soft\ContentSync> dotnet new tool-manifest PS C:\Soft\ContentSync> dotnet nuget add source -n Sitecore https://nuget.sitecore.com/resources/v3/index.json PS C:\Soft\ContentSync> dotnet tool install Sitecore.CLI PS C:\Soft\ContentSync> dotnet sitecore cloud login If the above error occurs, you will need to run a different command to resolve the issue. PS C:\Soft\ContentSync> dotnet sitecore init now, Again run above command to open and authenticate with XM Cloud. It will be there a...

Insert,delete,update,select using angularjs with mvc

Asp.net MVC with AngularJS is boom in the current environment of development in .net platform.
I am going to show you how to insert delete and update data by using angularjs with asp.net mvc.

I will explain you step by step to create a projet by using angularjs with mvc.

Details of point to be discuss in this tutorial is as follows.

1.   How to create Project using asp.net mvc with AngularJS.
2.   Installing the package of AngularJS in project of Asp.net MVC.
3.   Process to create module, services and controller in AngularJs.
4.   How to extract data from server using C#.
5.   How to bind data on HTML Page using AngularJS method like bind,fill and load from server side.
6.   How to do perform operation to insert, delete,update and edit by using AngularJS

Before starting of project we should know some basic information about AngularJS. Which can help us to understand and developed best application by using this technologies.

What is angularjs?
AngularJS is a client side scriptng language which can help us to develop dynamic single page application.It provide dynamic data binding in html .It has unit testable so this is trend in market.

Now we should know about advantage and limitation of angularjs
Now you may check some advantages of AngularJS .
1.   Scope
2.   Controller
3.   Databinding
4.   Services
5.   Unit Testable Code
6.   Dependency Injection
7.   Single Page application development

Some of limitation of AngularJS which developer should know before developing any application using this technologies.
1.   Not Secure :- Server side authentication and authorization is must as it is all code written in java script.
2.   Complex Life Cycle : - AngularJS Application life cycle is very complex.
3.   Not Degradebale  :-AngularJS will not work when you off javascript in browser.

Let’s get start to create project using visual studio 2012.

First you need to open visual studio 2012.Now click on file menu and then go to create New Project>>Select Asp.net MVC 4 from windows and give the suitable project name.

Now Select Basic option from new open window which is shown below.
Add caption


Now Add AngularJS package in your project by using nugget package console.

Step to install angularjs package in project by below command.
PM>Install-Package angularjs
Another one is
PM>Install-Package Angularjs.Route
In this way you complete to add angularjs libarary in your project.

Step1 :-   First we need to create model in asp.net mvc project .model is used for database record we can create first model using entity framework.

Now, I am creating employee table by using ID is primary key and it is a identity.

Create table dbo.employee
(
ID int identity(1,1),
Name nvarchar(100) NULL,
EmailID nvarchar(50) Null,
Address navarchar(200) NULL,
PRIMARY KEY CLUSTURED (ID ASC)
)
Now ,by using entity framework add entity data model.


And select database model from dropdown as you may see in below image .Now we created model .


 Step2 :  In this step now I am going to create controller in mvc project. Controller name is HomeController,


In this controller created method of insert delete and update method for this please see  bellow method.

public ActionResult Index()
      {
          return View();
      }

      public JsonResult getDetails()
      {
          using (SampleDBEntities dataContext = new SampleDBEntities())
          {
              var employeeList = dataContext.Employees.ToList();
              return Json(employeeList, JsonRequestBehavior.AllowGet);
          }
      }

      public JsonResult getEmpByNo(string EmpNo)
      {
          using (SampleDBEntities dataContext = new SampleDBEntities())
          {
              int no = Convert.ToInt32(EmpNo);
              var employeeList = dataContext.Employees.Find(no);
              return Json(employeeList, JsonRequestBehavior.AllowGet);
          }
      }
      public string UpdateEmp(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  int no = Convert.ToInt32(Emp.Id);
                  var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
                  employeeList.name = Emp.name;
                  employeeList.mobil_no = Emp.mobil_no;
                  employeeList.email = Emp.email;
                  dataContext.SaveChanges();
                  return "Employee Has been Updated";
              }
          }
          else
          {
              return "Invalid Operations";
          }
      }
      public string AddEmp(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  dataContext.Employees.Add(Emp);
                  dataContext.SaveChanges();
                  return "Employee Has been Updated";
              }
          }
          else
          {
              return "Invalid Operations";
          }
      }

      public string DeleteEmp(Employee Emp)
      {
          if (Emp != null)
          {
              using (SampleDBEntities dataContext = new SampleDBEntities())
              {
                  int no = Convert.ToInt32(Emp.Id);
                  var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
                  dataContext.Employees.Remove(employeeList);
                  dataContext.SaveChanges();
                  return "Employee Has been Deleted";
              }
          }
          else
          {
              return "Invalid Operation";
          }
      }

I have created some method in above class which is described in below section .

getDetails() :-This is use to get all details of all employee in JSON format.
getEmpByNo() :- This method is use for to get details of employee by specified ID.
updateEmp() :- This method is used for to update the existing employee data in database.
AddEmp() :- This method is used to add new employee details in database.
DeleteEmp() :- This method is use for delete existing employee from database.

ADD view :-
Now We need to add View for the above controller . so right click on Index() method and click on add view from pane , it will automatically add index.cshtml file in your view folder.
For angularjs  I am using the following directives for the operations.

Ng-Click : This directive allow us fire click event when you click so we can do any operation after firing of click event.

Ng-Controller : - This is use to attach controller class with view.

Ng-Repeat  :-  It is use to instantiate template per item from a collection. Each item has it’s own scope.$index is use to set item index.

Ng-Model :- it is use to binding the view  into model.

Now you may see the below design of index page.

<div ng-controller="myCntrl">
     <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

   <h1> Employee Details Page</h1>

    <br />

        <input type="button" class="btnAdd" value=" Add Employee" ng-click="AddEmpDiv()" />

    <div class="divList">
        <p class="divHead">Employee Details list</p>
        <table cellpadding="12" class="table table-bordered table-hover">
            <tr>
                <td><b>ID</b></td>
                <td><b>Name</b></td>
                <td><b>Email</b></td>
                <td><b>Address</b></td>
                <td><b>Actions</b></td>
            </tr>
            <tr ng-repeat="employee in employees">
                <td>
                    {{employee.Id}}
                </td>
                <td>
                    {{employee.name}}
                </td>
                <td>
                    {{employee.email}}
                </td>
                <td>
                    {{employee.Address}}
                </td>
                <td>
                    <span ng-click="editEmp(employee)" class="btnAdd">Edit</span>
                    <span ng-click="deleteEmp(employee)" class="btnRed">Delete</span>
                </td>
            </tr>
        </table>
    </div>

    <div ng-show="divEmployee">
        <p class="divHead">{{Action}} Employee</p>
        <table>
            <tr>
                <td><b>Employee Id</b></td>
                <td>
                    <input type="text" disabled="disabled" ng-model="employeeId" />
                </td>
            </tr>
            <tr>
                <td><b>Employee Name</b></td>
                <td>
                    <input type="text" ng-model="employeeName" />
                </td>
            </tr>
            <tr>
                <td><b>Email ID</b></td>
                <td>
                    <input type="text" ng-model="employeeEmail" />
                </td>
            </tr>
            <tr>
                <td><b>Address</b></td>
                <td>
                    <input type="text" ng-model="employeeAddress" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" class="btnAdd" value="Save" ng-click="AddUpdateEmp()" />
                </td>
            </tr>
        </table>
    </div>
</div>

Step 3:  Now going to create MVC code for AngularJS. MVC means model view and controller .
Create javascript file name as
1.   Model.js
2.   Controller.js
3.   Service.js

Model.js :-
Angular.Modules : - It is a container part of an applications and use to configure $injector.

Example is : var app=angular.module(“myFirstApp”,[]);

Service.JS: - In this file I am going to create services for different
operations. in this services we use $http to call server side method.


app.service("myService", function ($http) {

    //get All Eployee Details
    this.getEmployees = function () {
        debugger;
        return $http.get("Home/GetDetails");
    };

    // get Employee By Id
    this.getEmployee = function (employeeID) {
        var response = $http({
            method: "post",
            url: "Home/getEmpByNo",
            params: {
                id: JSON.stringify(employeeID)
            }
        });
        return response;
    }

    // Update Employee
    this.updateEmp = function (employee) {
        var response = $http({
            method: "post",
            url: "Home/UpdateEmp",
            data: JSON.stringify(employee),
            dataType: "json"
        });
        return response;
    }

    // Add Employee
    this.AddEmp = function (employee) {
        var response = $http({
            method: "post",
            url: "Home/AddEmp",
            data: JSON.stringify(employee),
            dataType: "json"
        });
        return response;
    }

    //Delete Employee
    this.DeleteEmp = function (employeeId) {
        var response = $http({
            method: "post",
            url: "Home/DeleteEmp",
            params: {
                employeeId: JSON.stringify(employeeId)
            }
        });
        return response;
    }

Controller.JS: - I have used this file to call services. Please see below how I called service in controller js file.

app.controller("myCntrl", function ($scope, myService) {
    $scope.divEmp = false;
    GetAllEmployee();
    //To Get All Data from table
    function GetAllEmployee() {
        debugger;
        var getData = myService.getEmployees();
        debugger;
        getData.then(function (emp) {
            $scope.employees = emp.data;
        },function () {
            alert('Error in getting records');
        });
    }

    $scope.editEmployee = function (employee) {
        debugger;
        var getData = myService.getEmployee(employee.Id);
        getData.then(function (emp) {
            $scope.employee = emp.data;
            $scope.employeeId = employee.Id;
            $scope.employeeName = employee.name;
            $scope.employeeEmail = employee.email;
            $scope.employeeAge = employee.Age;
            $scope.Action = "Update";
            $scope.divEmployee = true;
        },
        function () {
            alert('Error in getting records');
        });
    }

    $scope.AddUpdateEmployee = function ()
    {
        debugger;
        var Employee = {
            Name: $scope.employeeName,
            Email: $scope.employeeEmail,
            Age: $scope.employeeAge
        };
        var getAction = $scope.Action;

        if (getAction == "Update") {
            Employee.Id = $scope.employeeId;
            var getData = myService.updateEmp(Employee);
            getData.then(function (msg) {
                GetAllEmployee();
                alert(msg.data);
                $scope.divEmployee = false;
            }, function () {
                alert('Error in updating record');
            });
        } else {
            var getData = myService.AddEmp(Employee);
            getData.then(function (msg) {
                GetAllEmployee();
                alert(msg.data);
                $scope.divEmployee = false;
            }, function () {
                alert('Error in adding record');
            });
        }
    }

    $scope.AddEmployeeDiv=function()
    {
        ClearFields();
        $scope.Action = "Add";
        $scope.divEmployee = true;
    }

    $scope.deleteEmployee = function (employee)
    {
        var getData = myService.DeleteEmp(employee.Id);
        getData.then(function (msg) {
            GetAllEmployee();
            alert('Employee Deleted');
        },function(){
            alert('Error in Deleting Record');
        });
    }

    function ClearFields() {
        $scope.employeeId = "";
        $scope.employeeName = "";
        $scope.employeeEmail = "";
        $scope.employeeAge = "";
    }
});
Step 4: - in this step now we need to call js file in html file. I am going to call js file in layout.cshtml page.
Please see below code to understand .Now we success fully created all those process which we required to insert, delete, update and select  data and show on user interface by using angularJS with Asp.net MVC.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />

   <title>@ViewBag.Title</title>

    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Content/Angular/Module.js"></script>
    <script src="~/Content/Angular/Service.js"></script>
    <script src="~/Content/Angular/Controller.js"></script>
    @Styles.Render("~/Content/css")
    <style>
      
    </style>
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")

    @RenderSection("scripts", required: false)
</body>
</html>




Comments

Popular posts from this blog

Socket Programming in Python

  Example of socket programing in python. Here's a simple example of socket programming in Python: Server Side Code import socket # Create a socket object serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Get local machine name host = socket.gethostname()                            port = 9999 # Bind to a port serversocket.bind((host, port))                                   # Listen to at most 1 connection at a time serversocket.listen(1) print("Server is ready to receive") while True:     # Establish a connection     clientsocket,addr = serversocket.accept()           print("Got a connection from", addr)     clientsocket.send(b"Thank you for connecting")     clientsocket.close() Client Side Code import socket # Create a socket obje...

Homework 3.3 MongoDB for DBAs

MongoDB Homework 3.3 for DBAs. She below image for the answer of homework 3.3.

How do I start learning on AI

To start learning AI, you can follow these steps: Choose a programming language: Python is the most popular language for AI and machine learning, but you can also use R or other languages. Get familiar with basic mathematics and statistics: You should have a basic understanding of linear algebra, calculus, and probability. Learn about artificial neural networks: Neural networks are the building blocks of deep learning and are essential to understanding AI. Get hands-on experience: The best way to learn AI is by working on projects. There are many online resources with tutorials and open-source projects to get you started. Participate in online communities: AI has a thriving online community where you can ask questions, share your work, and connect with others. Keep up with the latest developments: AI is a rapidly advancing field, and it's important to stay up-to-date with the latest developments and trends. Remember, learning AI requires time, effort, and practice, but it is a valu...

AngularJS Best Practice

Best Practice to write AngularJS Program code. This is very useful code to communicate with webApi or other any any services. You may learn here more about different services. var commonModule = angular.module('common', ['ngRoute']); var mainModule = angular.module('main', ['common']); commonModule.factory('viewModelHelper', function ($http, $q, $window, $location) { return MyApp.viewModelHelper($http, $q, $window, $location); }); commonModule.factory('validator', function () { return valJs.validator(); }); mainModule.controller("indexViewModel", function ($scope, $http, $q, $routeParams, $window, $location, viewModelHelper) { var self = this; $scope.sessionName = "ASP.NET MVC with Angular JS"; $scope.speakerName = "Shashi Keshar"; }); (function (myApp) { var viewModelHelper = function ($http, $q, $window, $location) { var self = this; self.modelIsValid = true...