Display Binary Image from database using AngularJS and Web Service in ASP.Net

skp
 
on Mar 22, 2019 12:15 AM
Sample_954336.zip
4885 Views

Good Morning,

How to retrieve and display an image from the database based on employee_id with a search button using angularjs in asp.net with web service without mvc

here I'm using web service

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Script.Services;

namespace Demo_Web
{
    /// <summary>
    /// Summary description for EmployeeService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {
        public EmployeeService()
        {
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetEmployeeDetail()
        {
            List<Employee> empList = new List<Employee>();
            using (SqlConnection con = new SqlConnection("Integrated Security=SSPI; Persist Security Info=False; Initial Catalog=Employee; Data Source=STAGINGSERVER"))
            {
                SqlCommand cmd = new SqlCommand("select * from emp", con);
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Employee empObj = new Employee();
                    empObj.EmpID = Convert.ToInt32(dr["EmpID"]);
                    empObj.Name = dr["Name"].ToString();
                    empObj.Gender = dr["Gender"].ToString();
                    empObj.Salary = dr["Salary"].ToString();
                    empObj.Address = dr["Address"].ToString();
                    empList.Add(empObj);
                }
            }
            JavaScriptSerializer jsObj = new JavaScriptSerializer();
            jsObj.Serialize(empList);
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Demo_Web.App_Code
{
    public class Employee
    {
        public int EmpID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Salary { get; set; }
        public string Address { get; set; }
        public Employee()
        {
        }
    }
}

 

<!DOCTYPE html>
<html ng-app="myModule">
<head>
    <title></title> 
</head>
<body style="font-family:Arial; font-size:medium; color:darkblue">
    <div ng-controller="myCont">
        <br />
        <table>
            <tr>
                <th>EmpID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Salary</th>
                <th>Address</th>
            </tr>
            <tr ng-repeat="e in employees">
                <td>{{e.EmpID}}</td>
                <td>{{e.Name}}</td>
                <td>{{e.Gender}}</td>
                <td>{{e.Salary}}</td>
                <td>{{e.Address}}</td>
            </tr>
        </table>
    </div>
</body>
</html>

 

var myApp = angular.module("myModule", []);
var myController = function ($scope, $http) {
    $http.post('EmployeeService.asmx/GetEmployeeDetail')
    .then(function (response) {
        $scope.employees = response.data;
    });
};
myApp.controller("myCont", myController);

I'm getting  4 errors in EmployeeService.asmx file and the errors include as follows :

List<Employee> empList = new List<Employee>();

 Employee empObj = new Employee(); 

To specify errors, I have highlighted those in bold and italic.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Mar 27, 2019 04:26 AM

Hi skp,

Check this example. Now please take its reference and correct your code.

Using the below article i have created the example.

Save and Retrieve Image from SQL Server Database in ASP.Net MVC

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script type="text/javascript">
    var app = angular.module("MyApp", [])
    app.controller("MyController", function ($scope, $http) {
        $scope.myData = {};
        $scope.IsVisible = false;
        $scope.ShowHide = function () {
            $scope.IsVisible = $scope.IsVisible ? false : true;
        }
        $scope.myData.doClick = function (item, event) {
            var id = $scope.Id != '' ? $scope.Id : 0;
            $http.post('FileService.asmx/GetEmployeeDetail', { id: id }, { headers: { 'Content-Type': 'application/json' }
            }).success(function (data, status, headers, config) {
                var result = JSON.parse(data.d);
                $scope.myData.fromServer = result;
            }).error(function (data, status, headers, config) {
            });
        }
    });        
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <input type="text" ng-model="Id" ng-change="myData.doClick(item, $event)" />
    <button type="button" ng-click="ShowHide()">
        Search</button>
    <br />
    <br />
    <table ng-show="IsVisible">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Image</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="image in myData.fromServer">
                <td>{{image.ID}}</td>
                <td>{{image.Name}}</td>
                <td><img ng-src="{{'data:image/png;base64,'+image.Data}}" /></td>
            </tr>
        </tbody>
    </table>
</div>

WebService

C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class FileService : System.Web.Services.WebService
{
    public FileService()
    {
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public string GetEmployeeDetail(int id)
    {
        List<File> empList = new List<File>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("SELECT Id,Name,Data FROM tblFiles WHERE Id = @Id OR @Id IS NULL", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Id", id > 0 ? id : (object)DBNull.Value);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                File empObj = new File();
                empObj.ID = Convert.ToInt32(dr["Id"]);
                empObj.Name = dr["Name"].ToString();
                empObj.Data = Convert.ToBase64String((byte[])dr["Data"]);
                empList.Add(empObj);
            }
        }
        JavaScriptSerializer jsObj = new JavaScriptSerializer();
        return jsObj.Serialize(empList);
    }
}

VB.Net

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Script.Services
Imports System.Web.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class FileService
    Inherits System.Web.Services.WebService

    <WebMethod()>
    <ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json)>
    Public Function GetEmployeeDetail(ByVal id As Integer) As String
        Dim empList As List(Of File) = New List(Of File)()

        Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
            Dim cmd As SqlCommand = New SqlCommand("SELECT Id,Name,Data FROM tblFiles WHERE Id = @Id OR @Id IS NULL", con)
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@Id", If(id > 0, id, CObj(DBNull.Value)))
            con.Open()
            Dim dr As SqlDataReader = cmd.ExecuteReader()

            While dr.Read()
                Dim empObj As File = New File()
                empObj.ID = Convert.ToInt32(dr("Id"))
                empObj.Name = dr("Name").ToString()
                empObj.Data = Convert.ToBase64String(CType(dr("Data"), Byte()))
                empList.Add(empObj)
            End While
        End Using

        Dim jsObj As JavaScriptSerializer = New JavaScriptSerializer()
        Return jsObj.Serialize(empList)
    End Function
End Class

Screenshot