Saturday 4 March 2017

MVC - VIew - Get user role

Watch this example on YouTube

1. View
@if(Html.GetRole() == "Admin")
{
    <h1>Hi admin!!!!</h1>
}

2. Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCIntranetTest.Models;

namespace System.Web.Mvc
{
    public static class SomeClassToAccess
    {
        public static string GetRole(this HtmlHelper html)
        {
            CompanyEntities db = new CompanyEntities();
            string CurrentUser = HttpContext.Current.User.Identity.Name.ToString();
            CurrentUser = CurrentUser.ToLower().Replace("living\\", "");
            string role = db.GetUserRole(CurrentUser).FirstOrDefault();
            return role;
        }
    }
}

3. Stored Procedure
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE GetUserRole
    @LanID Varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT        UserRoles.RoleName
    FROM            Users INNER JOIN
                             UserRoles ON Users.RoleID = UserRoles.RoleID
    WHERE        (Users.LanID = @LanID)
END
GO

No comments:

Post a Comment