Thursday, January 16, 2020

angularjs-crud operation using asp net mvc

First, we create an MVC project. Go to File-> New-> Project and select “ASP.NET Web Application”.

Now, select MVC template for the project.

In Solution Explorer window, we can see the structure of our project.

Now, we add the model classes in our project. We have an Employee table which we will use in our project and implement the CRUD operation on.

CREATE TABLE [dbo].[Employee](  
[Emp_Id] [int] IDENTITY(1,1) NOT NULL,  
[Emp_Name] [varchar](max) NULL,  
[Emp_City] [varchar](max) NULL,  
[Emp_Age] [int] NULL,  
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
(  
[Emp_Id] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  
GO  




 

For database CRUD operation, we will use the Entity Framework Data First approach. For this, right click on “Model” folder and click on “New Item” option.


Now, select “ADO.NET Entity Data Model” and name it as “EmployeeModel”.

Establish a connection with “SQL Server Database” Engine.


Select Employee table Entity Data Model Wizard and click on Finish button.

Now, go to your project’s Model folder where you can see that Employee Model class has been created. So, you have successfully created a connection with database.


After this, we download and install the AngularJS package. Right click on Project Name and select “Manage NuGet Packages” option and download the AngularJS packages.


In Scripts folder, you can find that AngularJS files have been installed successfully.

Now, we create the Employee Controller. So, right click on Controller Folder and create an empty Controller.

Now, copy and paste the following code into your Employee Controller section.

  1. using AngularCRUD.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace AngularCRUD.Controllers {  
  8.     public class EmployeeController: Controller {  
  9.         // GET: Employee  
  10.         public ActionResult Index() {  
  11.                 return View();  
  12.             }  
  13.             /// <summary>  
  14.             ///   
  15.             /// Get All Employee  
  16.             /// </summary>  
  17.             /// <returns></returns>  
  18.         public JsonResult Get_AllEmployee() {  
  19.                 using(DemoEntities Obj = new DemoEntities()) {  
  20.                     List < Employee > Emp = Obj.Employees.ToList();  
  21.                     return Json(Emp, JsonRequestBehavior.AllowGet);  
  22.                 }  
  23.             }  
  24.             /// <summary>  
  25.             /// Get Employee With Id  
  26.             /// </summary>  
  27.             /// <param name="Id"></param>  
  28.             /// <returns></returns>  
  29.         public JsonResult Get_EmployeeById(string Id) {  
  30.                 using(DemoEntities Obj = new DemoEntities()) {  
  31.                     int EmpId = int.Parse(Id);  
  32.                     return Json(Obj.Employees.Find(EmpId), JsonRequestBehavior.AllowGet);  
  33.                 }  
  34.             }  
  35.             /// <summary>  
  36.             /// Insert New Employee  
  37.             /// </summary>  
  38.             /// <param name="Employe"></param>  
  39.             /// <returns></returns>  
  40.         public string Insert_Employee(Employee Employe) {  
  41.                 if (Employe != null) {  
  42.                     using(DemoEntities Obj = new DemoEntities()) {  
  43.                         Obj.Employees.Add(Employe);  
  44.                         Obj.SaveChanges();  
  45.                         return "Employee Added Successfully";  
  46.                     }  
  47.                 } else {  
  48.                     return "Employee Not Inserted! Try Again";  
  49.                 }  
  50.             }  
  51.             /// <summary>  
  52.             /// Delete Employee Information  
  53.             /// </summary>  
  54.             /// <param name="Emp"></param>  
  55.             /// <returns></returns>  
  56.         public string Delete_Employee(Employee Emp) {  
  57.                 if (Emp != null) {  
  58.                     using(DemoEntities Obj = new DemoEntities()) {  
  59.                         var Emp_ = Obj.Entry(Emp);  
  60.                         if (Emp_.State == System.Data.Entity.EntityState.Detached) {  
  61.                             Obj.Employees.Attach(Emp);  
  62.                             Obj.Employees.Remove(Emp);  
  63.                         }  
  64.                         Obj.SaveChanges();  
  65.                         return "Employee Deleted Successfully";  
  66.                     }  
  67.                 } else {  
  68.                     return "Employee Not Deleted! Try Again";  
  69.                 }  
  70.             }  
  71.             /// <summary>  
  72.             /// Update Employee Information  
  73.             /// </summary>  
  74.             /// <param name="Emp"></param>  
  75.             /// <returns></returns>  
  76.         public string Update_Employee(Employee Emp) {  
  77.             if (Emp != null) {  
  78.                 using(DemoEntities Obj = new DemoEntities()) {  
  79.                     var Emp_ = Obj.Entry(Emp);  
  80.                     Employee EmpObj = Obj.Employees.Where(x => x.Emp_Id == Emp.Emp_Id).FirstOrDefault();  
  81.                     EmpObj.Emp_Age = Emp.Emp_Age;  
  82.                     EmpObj.Emp_City = Emp.Emp_City;  
  83.                     EmpObj.Emp_Name = Emp.Emp_Name;  
  84.                     Obj.SaveChanges();  
  85.                     return "Employee Updated Successfully";  
  86.                 }  
  87.             } else {  
  88.                 return "Employee Not Updated! Try Again";  
  89.             }  
  90.         }  
  91.     }  
  92. }  

After creating the Controller, now, we create a View. Right click on Index method and create an Empty View.



Paste the following code into the Index View:

  1. @{  
  2. ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <style>  
  6. .btn-space {  
  7. margin-left: -5%;  
  8. background-color: cornflowerblue;  
  9. font-size: large;  
  10. }  
  11. </style>  
  12. <h2>Index</h2>  
  13. <div ng-app="myApp">  
  14.     <div ng-controller="myCtrl" ng-init="GetAllData()" class="divList">  
  15.         <p class="divHead">List of Employee</p>  
  16.         <table cellpadding="12" class="table table-bordered table-hover">  
  17.             <tr>  
  18.                 <td>  
  19.                     <b>ID</b>  
  20.                 </td>  
  21.                 <td>  
  22.                     <b>Name</b>  
  23.                 </td>  
  24.                 <td>  
  25.                     <b>City</b>  
  26.                 </td>  
  27.                 <td>  
  28.                     <b>Age</b>  
  29.                 </td>  
  30.                 <td>  
  31.                     <b>Actions</b>  
  32.                 </td>  
  33.             </tr>  
  34.             <tr ng-repeat="Emp in employees">  
  35.                 <td>  
  36. {{Emp.Emp_Id}}  
  37. </td>  
  38.                 <td>  
  39. {{Emp.Emp_Name}}  
  40. </td>  
  41.                 <td>  
  42. {{Emp.Emp_City}}  
  43. </td>  
  44.                 <td>  
  45. {{Emp.Emp_Age}}  
  46. </td>  
  47.                 <td>  
  48.                     <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />  
  49.                     <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />  
  50.                 </td>  
  51.             </tr>  
  52.         </table>  
  53.         <div class="form-horizontal" role="form">  
  54.             <div class="container">  
  55.                 <div class="row">  
  56.                     <h2>  
  57.                         <span id="spn">Add New Employee</span>  
  58.                     </h2>  
  59.                 </div>  
  60.                 <div class="row">  
  61.                     <div class="col-sm-6 col-lg-4">  
  62.                         <div class="form-group">  
  63.                             <label class="col-md-4 control-label">Name:</label>  
  64.                             <div class="col-md-8">  
  65.                                 <input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="EmpName">  
  66.                                 </div>  
  67.                             </div>  
  68.                         </div>  
  69.                         <div class="col-sm-6 col-lg-4">  
  70.                             <div class="form-group">  
  71.                                 <label class="col-md-4 control-label">City:</label>  
  72.                                 <div class="col-md-8">  
  73.                                     <input type="text" class="form-control" id="inputPassword" placeholder="City" ng-model="EmpCity">  
  74.                                     </div>  
  75.                                 </div>  
  76.                             </div>  
  77.                             <div class="col-sm-6 col-lg-4">  
  78.                                 <div class="form-group">  
  79.                                     <label class="col-md-4 control-label">Age:</label>  
  80.                                     <div class="col-md-8">  
  81.                                         <input type="text" class="form-control" id="inputLabel3" placeholder="Age" ng-model="EmpAge">  
  82.                                         </div>  
  83.                                     </div>  
  84.                                 </div>  
  85.                             </div>  
  86.                             <div class="row">  
  87.                                 <div class="col-sm-6 col-lg-4">  
  88.                                     <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />  
  89.                                 </div>  
  90.                             </div>  
  91.                         </div>  
  92.                     </div>  
  93.                 </div>  
  94. @Html.Hidden("EmpID_")  
  95.   
  96.             </div>  

For CRUD operations in AngularJS, we create a JavaScript file, write the code into that file, and implement this file into our Index View.

First, create a JavaScript file and copy the following code.


JavaScript code

  1. var app = angular.module("myApp", []);  
  2. app.controller("myCtrl"function($scope, $http) {  
  3.     debugger;  
  4.     $scope.InsertData = function() {  
  5.         var Action = document.getElementById("btnSave").getAttribute("value");  
  6.         if (Action == "Submit") {  
  7.             $scope.Employe = {};  
  8.             $scope.Employe.Emp_Name = $scope.EmpName;  
  9.             $scope.Employe.Emp_City = $scope.EmpCity;  
  10.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  11.             $http({  
  12.                 method: "post",  
  13.                 url: "http://localhost:39209/Employee/Insert_Employee",  
  14.                 datatype: "json",  
  15.                 data: JSON.stringify($scope.Employe)  
  16.             }).then(function(response) {  
  17.                 alert(response.data);  
  18.                 $scope.GetAllData();  
  19.                 $scope.EmpName = "";  
  20.                 $scope.EmpCity = "";  
  21.                 $scope.EmpAge = "";  
  22.             })  
  23.         } else {  
  24.             $scope.Employe = {};  
  25.             $scope.Employe.Emp_Name = $scope.EmpName;  
  26.             $scope.Employe.Emp_City = $scope.EmpCity;  
  27.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  28.             $scope.Employe.Emp_Id = document.getElementById("EmpID_").value;  
  29.             $http({  
  30.                 method: "post",  
  31.                 url: "http://localhost:39209/Employee/Update_Employee",  
  32.                 datatype: "json",  
  33.                 data: JSON.stringify($scope.Employe)  
  34.             }).then(function(response) {  
  35.                 alert(response.data);  
  36.                 $scope.GetAllData();  
  37.                 $scope.EmpName = "";  
  38.                 $scope.EmpCity = "";  
  39.                 $scope.EmpAge = "";  
  40.                 document.getElementById("btnSave").setAttribute("value""Submit");  
  41.                 document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";  
  42.                 document.getElementById("spn").innerHTML = "Add New Employee";  
  43.             })  
  44.         }  
  45.     }  
  46.     $scope.GetAllData = function() {  
  47.         $http({  
  48.             method: "get",  
  49.             url: "http://localhost:39209/Employee/Get_AllEmployee"  
  50.         }).then(function(response) {  
  51.             $scope.employees = response.data;  
  52.         }, function() {  
  53.             alert("Error Occur");  
  54.         })  
  55.     };  
  56.     $scope.DeleteEmp = function(Emp) {  
  57.         $http({  
  58.             method: "post",  
  59.             url: "http://localhost:39209/Employee/Delete_Employee",  
  60.             datatype: "json",  
  61.             data: JSON.stringify(Emp)  
  62.         }).then(function(response) {  
  63.             alert(response.data);  
  64.             $scope.GetAllData();  
  65.         })  
  66.     };  
  67.     $scope.UpdateEmp = function(Emp) {  
  68.         document.getElementById("EmpID_").value = Emp.Emp_Id;  
  69.         $scope.EmpName = Emp.Emp_Name;  
  70.         $scope.EmpCity = Emp.Emp_City;  
  71.         $scope.EmpAge = Emp.Emp_Age;  
  72.         document.getElementById("btnSave").setAttribute("value""Update");  
  73.         document.getElementById("btnSave").style.backgroundColor = "Yellow";  
  74.         document.getElementById("spn").innerHTML = "Update Employee Information";  
  75.     }  
  76. })  

Now, provide the references of AngularJS and AngularCode file that we created into Index View.


Now, I think our project is ready to work. So, let’s run the application. Press F5 and you can see that following screen will be visible on your browser.




Tuesday, September 9, 2014

How to implement ASP.NET Membership into a new database

Scenarios

Almost of the systems created will have a function to login to manage all of its data, it called with a namely is Login function. So, Microsoft created a component as a template to do this work to save your time when building a new system.

You want to work with this function, then firstly you need to know how to integrate it into your SQL database.

  • Step 1: Do the easily work to create the new database in SQL server.
  • Step 2: Once your database has been created, then you will do the work to integrate the membership in to its.
  • Step 3: Open the .NET Framework folder putted inside window folder as the path:C:\Windows\Microsoft.NET\Framework\v4.0.30319 (depends on your .NET framework version then your path will different), then run the application namely aspnet_regsql.exe.

    img1

  • Step 4: It will show an ASP.NET SQL Server Setup Wizard dialog. Click the Next button to go to the next step. 

    img2

  • Step 5: Choose Configure SQL Server for application services if you want to apply this function to the new database. Otherwise, choose Remove application services information from an existing database if you want to remove this function from a database which is implementing it. In this guide I will chose option 1 is implementing it to the new one database.

    Select option 1 and clicking to Next button, it will show a dialog as in step 6.

  • Step 6: You need to put the information of your server and then choosing the database that you want to implement this function.

    img3

    Once you selected the database, then clicking to Next button. Click Next button one more time to confirm you exactly want to implement this function into selected database. Waiting some seconds before the work is done. Click Finish button to complete your work.

  • Step 7: Open your SQL server to check the result. If your work is successfully then your db will has some tables as the screenshot. 

    img4

Hope that helps.

Tuesday, April 22, 2014

How to save an image using the image URL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO.MemoryStream;
using System.Drawing.Imaging;
using System.Net;
using System.IO.FileStream;
public partial class Default11 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
        string urlToDownload = "http://www.google.co.in/images/srpr/nav_logo14.png";
        // May be you need to add some code to determine the type of the image
        string pathToSave = Server.MapPath("~/") + "/saved.png";
        // Download it
        WebClient client = new WebClient();
        client.DownloadFile(urlToDownload, pathToSave);
    }
)

Sunday, April 20, 2014

Validate ASP.Net CheckBoxList control using JavaScript (Select atleast one item)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default11.aspx.cs" Inherits="Default11" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
<script type = "text/javascript">
    var atLeast = 1
    function ValidateCheckBoxList() {
        var CHK = document.getElementById("<%=CheckBoxList1.ClientID%>");
        var checkbox = CHK.getElementsByTagName("input");
        var counter = 0;
        for (var i = 0; i < checkbox.length; i++) {
            if (checkbox[i].checked) {
                counter++;
            }
        }
        if (atLeast > counter) {
            alert("Please select atleast " + atLeast + " item(s)");
            return false;
        }
        return true;
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Text = "Apple" Value = "1"></asp:ListItem>
    <asp:ListItem Text = "Mango" Value = "2"></asp:ListItem>
    <asp:ListItem Text = "Orange" Value = "3"></asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="*Required"
ClientValidationFunction = "ValidateCheckBoxList"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Validate ASP.Net ListBox control using JavaScript

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default11.aspx.cs" Inherits="Default11" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
<script type = "text/javascript">
    function ValidateListBox(sender, args) {
        var options = document.getElementById("<%=ListBox1.ClientID%>").options;
        for (var i = 0; i < options.length; i++) {
            if (options[i].selected == true) {
                args.IsValid = true;
                return;
            }
        }
        args.IsValid = false;
    }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
  
<asp:ListBox ID="ListBox1" runat="server" SelectionMode = "Multiple">
    <asp:ListItem Text = "Apple" Value = "1"></asp:ListItem>
    <asp:ListItem Text = "Mango" Value = "2"></asp:ListItem>
    <asp:ListItem Text = "Orange" Value = "3"></asp:ListItem>
</asp:ListBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="*Required"
ClientValidationFunction = "ValidateListBox"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

Saturday, April 19, 2014

Date Range Validation in AJAX CalendarExtender Control using ASP.Net Range Validator

In this article I will explain how to implement Range Validation in ASP.Net AJAX Control Toolkit CalendarExtender Control.

 

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
   
    <asp:TextBox ID="txtDate" runat="server" ReadOnly = "true"></asp:TextBox>
    <br />
    <asp:RangeValidator runat="server" ID="RangeValidator1" Type="Date" ControlToValidate="txtDate" MaximumValue='09/20/2011' MinimumValue="09/01/2011"
    ErrorMessage="Date should be between 09/01/2011 and 09/20/2011" Display="Dynamic" />
   
    <cc1:CalendarExtender ID = "Calender1" runat = "server" TargetControlID = "txtDate"></cc1:CalendarExtender>
    <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" />
</form>


Above you will notice that I have an ASP.Net TextBox Control txtDate for which I have specified AJAX Control Toolkit CalendarExtender Control Calender1.



Also I have specified ASP.Net RangeValidator Control RangeValidator1 for the TextBox txtDate. This range validator will throw error when the selected date does not fit in the specified range.



In order to make the Range Validator work for the Dates. You need to specify the following paramaters



Type – Specifies that the range validations are for Dates.



MinimumValue – Specifies the minimum value of the range.



MaximumValue - Specifies the minimum value of the range.



 



Screenshot



Implement Range Validation in AJAX Control Toolkit CalendarExtender Control.