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

List of pipeline in Sitecore and it's example

 List of pipeline in Sitecore and it's example Sitecore uses a pipeline architecture to process requests and manage the flow of data within the system. Here is a list of some common pipelines in Sitecore, along with an example for each one: HttpRequestBegin: This pipeline processes the initial request made by a user to the Sitecore website and sets up the environment for processing the request. For example, it might determine the language for the request based on the user's browser settings or the URL . HttpRequestProcessed: This pipeline processes the request after it has been processed by Sitecore and is used to perform any post-processing operations, such as logging or error handling. For example, it might log the request information to a database for later analysis. RenderLayout: This pipeline processes the layout for a page and is responsible for rendering the components of the page, including the header, footer, and content areas. For example, it might retrieve the layout...

Fileupload using AngularJS in asp.net c#

Fileupload using AngularJS in asp.net c# AngularJS built-in ng-model directive. I added an attribute called ng-files in to the file input element. Now, I need to  create a directive in the controller matching with the attribute  The attribute has a function named getTheFiles() with a parameter $files . I’ll initialize the parameter $files in my directive and later call the function getTheFiles() using the controller’s scope, along with $files parameter. <!DOCTYPE html> <html> <head>   <title>AngularJS File Upoad Example with $http and FormData</title>   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script> </head> <body ng-app="fupApp">     <div ng-controller="fupController">         <input type="file" id="file1" name="file" multiple        ...

How Directives are compiled in angularjs?

AngularJS always operates on DOM node. We are not able to do any notice when HTML page loads. It parse automatically into DOM. Compilation of HTML happens in three steps which is pointed below. 1.    In angularjs $compile is use to traverse the DOM and looks for directive. It find each directive and add it into the list of directive. 2.    It is use to sort the list of directive by their priority when the entire DOM has been traversed. Each directive has own compilation function to be executed and each have chance to modify by itself. Each compile function return linking function and then it is use to composed into combined linking function and return it. 3.    $compile relations the template with the choice by calling the joint linking function from the earlier step. This in turn will request the connecting function of the separate directives, process listeners on the elements and set up $watch with the scope as each directive is organised to...

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...