Show Hide Button in Table based on Role using WebService in AngularJS

Last Reply 3 months ago By dharmendr

Posted 3 months ago

How to show hide Button in table row based on Role in ASP.Net using AngularJS

Show Hide Edit Button in GridView based on Role in ASP.Net using C# and VB.Net

Posted 3 months ago

Hi rani,

Using the below article i have created the example.

Show Hide Edit Button in GridView based on Role in ASP.Net using C# and VB.Net

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

For binding record i have used Northwind database that you can download using the link given below.

Download Northwind Database

HTML

Login

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link type="text/css" rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css' />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var loginApp = angular.module('LoginApp', []);
        loginApp.controller('LoginController', function ($scope, $http, $window) {
            $scope.Submit = function () {
                var userData = { username: $scope.Username, password: $scope.Password }
                $http.post('WebService.asmx/ValidateUser', userData)
                .then(function (response) {
                    if (response.data.d != "") {
                        $window.location.href = 'Home.htm?Role=' + response.data.d;
                    }
                });
            }
        });
    </script>
</head>
<body ng-app="LoginApp" ng-controller="LoginController">
    <section class="container">
        <div class="main_cont register">
            <div class="login-panel">
                <h3 class="login-heading"></h3>
                <div class="row">                       
                    <div class="col-md-12 col-sm-12">
                        <div class="form-group">
                            <input type="text" class="form-control" ng-model="Username" name="Name" placeholder="Username" value="" autocomplete="off" required/>
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-control" ng-model="Password" name="Password" placeholder="Password" value="" autocomplete="off" required/>
                        </div>
                        <div class="float-right">
                            <input type="button" class="btn btn-primary" ng-click="Submit()" value="Login" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</body>
</html>

Home

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link type="text/css" rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css' />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller('MyController', function ($scope, $http, $window) {
            $scope.Role = $window.location.search.split('=')[1];
            $http.post("WebService.asmx/BindEmployees", { headers: { 'Content-Type': 'application/json'} })
            .then(function (response) {
                $scope.Employees = eval(response.data.d);
            });
        });
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <table class="table table-bordered table-responsive">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>City</th>
                    <th>Country</th>
                    <th ng-show="Role=='Administrator'">Action</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in Employees">
                    <td>{{ employee.EmployeeId }}</td>
                    <td>{{ employee.FirstName }}</td>
                    <td>{{ employee.LastName }}</td>
                    <td>{{ employee.City }}</td>
                    <td>{{ employee.Country }}</td>
                    <td ng-show="Role=='Administrator'">
                        <input type="button" class="btn-primary" value="Edit" />
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

WebService

C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
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 WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string ValidateUser(string username, string password)
    {
        int userId = 0;
        string roles = string.Empty;
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("Validate_User");
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Username", username);
        cmd.Parameters.AddWithValue("@Password", password);
        cmd.Connection = con;
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        reader.Read();
        userId = Convert.ToInt32(reader["UserId"]);
        roles = reader["Roles"].ToString();
        con.Close();
        return roles;
    }

    [WebMethod]
    public string BindEmployees()
    {
        List<object> employees = new List<object>();
        string sql = "SELECT TOP 5 EmployeeID,FirstName,LastName,City,Country FROM Employees";
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr1"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand(sql))
            {
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new
                        {
                            EmployeeId = sdr["EmployeeID"],
                            FirstName = sdr["FirstName"],
                            LastName = sdr["LastName"],
                            City = sdr["City"],
                            Country = sdr["Country"]
                        });
                    }
                }
                conn.Close();
            }
            return (new JavaScriptSerializer().Serialize(employees));
        }
    }
}

VB.Net

Imports System
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
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 WebService
    Inherits System.Web.Services.WebService
    <WebMethod()>
    Public Function ValidateUser(ByVal username As String, ByVal password As String) As String
        Dim userId As Integer = 0
        Dim roles As String = String.Empty
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim con As SqlConnection = New SqlConnection(constr)
        Dim cmd As SqlCommand = New SqlCommand("Validate_User")
        cmd.CommandType = System.Data.CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@Username", username)
        cmd.Parameters.AddWithValue("@Password", password)
        cmd.Connection = con
        con.Open()
        Dim reader As SqlDataReader = cmd.ExecuteReader()
        reader.Read()
        userId = Convert.ToInt32(reader("UserId"))
        roles = reader("Roles").ToString()
        con.Close()
        Return roles
    End Function

    <WebMethod()>
    Public Function BindEmployees() As String
        Dim employees As List(Of Object) = New List(Of Object)()
        Dim sql As String = "SELECT TOP 5 EmployeeID,FirstName,LastName,City,Country FROM Employees"
        Using conn As SqlConnection = New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr1").ConnectionString
            Using cmd As SqlCommand = New SqlCommand(sql)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        employees.Add(New With {
                            .EmployeeId = sdr("EmployeeID"),
                            .FirstName = sdr("FirstName"),
                            .LastName = sdr("LastName"),
                            .City = sdr("City"),
                            .Country = sdr("Country")
                        })
                    End While
                End Using
                conn.Close()
            End Using

            Return (New JavaScriptSerializer().Serialize(employees))
        End Using
    End Function
End Class

Screenshot