Rehan Shah
Rehan Shah

Reputation: 1627

Rendering HTML Contents according to User Role?

For example: I have to two roles in my application.

1.Administrator // Can perform all CRUD operations on data.

2.Customer // Can only Read the existing data.

In case of returning view to the User according to there role ? Now I have a choice that create two separate views according to roles.

Let see some Code.

public ActionResult Index()
{
    var customers = _dbContext.Customers.Include(c => c.Type).ToList();
    if (User.IsInRole(userRole.IsAdministator))
    {
        return View("Admin_List_View", customers);
    } else
    {
        return View("Customer_ReadOnlyList_View" , customers);
    }
}

In the above code.I have two view.

1.Admin_List_View // This view contains all the Data along with Add,Delete,Update,Edit options.

2.Customer_ReadOnly_View // This view will only contains Readonly list.

So my question is that: In case of simple view i have to follow this approach by writing a separate view for a target roles.

But as it Possible to have a single view and assign the specific section of that to specfic role ?

Note: I am asking this question is that...In case of complex view that i don't have a choice to create another view from scratch for a particular role. So i am wondering that there is any way to play with the existing view.

For example: I have to roles.

Admin & customer

and

i have one view.

How to manage that one view for these to roles?

Upvotes: 1

Views: 624

Answers (2)

Rehan Shah
Rehan Shah

Reputation: 1627

More Detailed Answer:

public ActionResult Index()
{
    var customers = _dbContext.Customers.Include(c => c.Type).ToList();
    if (User.IsInRole(userRole.IsAdministator))
    {
        return View("Admin_List_View", customers);
    } else
    {
        return View("Customer_ReadOnlyList_View" , customers);
    }
}

In the above example. when have two roles and both roles have specfic view.

1.One way is:

to create two view for separate role for the above example: i had created two views

  • 1.Admin_List_View
  • 2.Customer_ReadOnlyList

2.2nd ways is:

to create sample view and assign html contents based on a user role.

For example:

I have to roles:

again i will say that:

1.AdminList 2.CustomerList.

and now i have only one view: index.cshtml

index.cshmtl

@model IEnumerable<Vidly.Models.Customer>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2 id="heading">Customers</h2>

// This Button is accessible to only admin.
@Html.ActionLink("Add New Customer" , "Add" , "Customer" )

@if (Model.Count() == 0)
{
    <p>No Customer is found.</p>
}
else
{
    <table id="customers" class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>Full Name</th>
                <th>Email Address</th>
                <th>Physical Addrses</th>
                <th>Type</th>

                     <th>Actions</th>   // This Column will be only accessible to 
 admin role.

               }
            </tr>
        </thead>
        @foreach (var item in Model)
        {
            <tbody>
                <tr>
                    <td>@item.FullName</td>
                    <td>@item.EmailAddress</td>
                    <td>@item.PhysicalAddress</td>
                    <td>@item.Type.TypeName</td>


                     // These Button will be only accessible to Admin 

                     // This is the Edit Button.
                    <td><button data-customer-id="@item.Id" class="btn btn-link js-delete">Edit</button></td>

                     // This is the Delete Button.
      <td><button data-customer-id="@item.Id" class="btn btn-link js-delete">Delete</button></td>





                </tr>
            </tbody>
        }
    </table>
}

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#customers").DataTable();
            $("#customers").on("click", ".js-delete", function () {
                var button = $(this);
                var result = confirm("Are you sure you want to delete this customer?");
                    function (result) {
                    if (result) {
                        $.ajax({
                            url: "/api/customers/" + button.attr("data-customer-id"),
                            method: "Delete",
                            success: function () {
                                button.parents("tr").remove();
                            },
                            error: function (xhr) {
                                alert("Something goes wrong." + " " + " Error Details " + xhr.status);
                            }

                        });
                    }
                });
            });
        });
    </script>
}

So This the entire view.

Now assigning specfic content to specfic Role:

@model IEnumerable<Vidly.Models.Customer>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2 id="heading">Customers</h2>

@if(User.IsRole("Admin")) // Checking that if the LoggedIn User is Admin or Not? if The User is Admin Dispay this "Add New Customer Link" Otherwise don't display it.
{

// This Button is accessible to only admin.
@Html.ActionLink("Add New Customer" , "Add" , "Customer" )


}

@if (Model.Count() == 0)
{
    <p>No Customer is found.</p>
}
else
{
    <table id="customers" class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>Full Name</th>
                <th>Email Address</th>
                <th>Physical Addrses</th>
                <th>Type</th>

                @if(User.IsRole("Admin")) // Again Checking That the User is Admin or not? if the User admin Display the table Header otherwise don't display it.
                {

                     <th>Actions</th>   // This Column will be only accessible to admin role.

               }
            </tr>
        </thead>
        @foreach (var item in Model)
        {
            <tbody>
                <tr>
                    <td>@item.FullName</td>
                    <td>@item.EmailAddress</td>
                    <td>@item.PhysicalAddress</td>
                    <td>@item.Type.TypeName</td>


                    @if(User.IsRole("Admin")) // Checking that the LoggedIn User is Admin or Not. If the User is Admin the Display these buttons otherwise don't Display it.
                    {

                         // These Button will be only accessible to Admin 

                         // This is the Edit Button.
                        <td><button data-customer-id="@item.Id" class="btn btn-link 
js-delete">Edit</button></td>

                         // This is the Delete Button.
                        <td><button data-customer-id="@item.Id" class="btn btn-link 
js-delete">Delete</button></td>


                   }

                </tr>
            </tbody>
        }
    </table>
}

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            $("#customers").DataTable();
            $("#customers").on("click", ".js-delete", function () {
                var button = $(this);
                var result = confirm("Are you sure you want to delete this customer?");
                    function (result) {
                    if (result) {
                        $.ajax({
                            url: "/api/customers/" + button.attr("data-customer-id"),
                            method: "Delete",
                            success: function () {
                                button.parents("tr").remove();
                            },
                            error: function (xhr) {
                                alert("Something goes wrong." + " " + " Error Details " + xhr.status);
                            }

                        });
                    }
                });
            });
        });
    </script>
}

Upvotes: 2

Strikegently
Strikegently

Reputation: 2461

Possible to have a single view and assign the specific section of that to specfic role ?

Yes. You can achieve this with Razor syntax which allows C# in your HTML. Prefix your C# statements with "@". See here.

In your View:

<button>Do Regular User Stuff</button>
@if(User.IsInRole("Admin") {
    <button>Do Admin Stuff</button>
}

Upvotes: 2

Related Questions