0

I am trying to remove certain web application buttons based on the user's permissions from the code-behind.

I tried to trigger a javascript onload to remove the designated DOM elements but the page would load first and then the DOM will be modified after. I want the DOM to be modified first before the page even loads.

  • What would stop the user from calling that action with a manual request? Just because the button is gone, doesn't mean the user can't activate its function. – Matt Rowland Jul 17 '19 at 18:27
  • If you have those permissions data in the viewmodel you could just wrap the button in a razor syntax if statement that checks the value of that data in your cshtml – Iskandar Reza Jul 17 '19 at 18:34
  • 4
    if i understand correctly then its simple as `@if (User.HasPermission) { //render }` – Steve Jul 17 '19 at 18:46
  • Possible duplicate of [How to show/hide an area within Razor View in ASP.NET MVC programmatically](https://stackoverflow.com/questions/6848055/how-to-show-hide-an-area-within-razor-view-in-asp-net-mvc-programmatically) – Heretic Monkey Jul 17 '19 at 19:48

1 Answers1

3

You're right in not wanting to rely on JavaScript for security, since any person knowledgeable in JavaScript can get around it.

Use Razor syntax in your cshtml page to not even put it there in the first place. The documentation is here, but essentially you just do this:

@if ([check if user has permission]) {
    <button>Do Something</button>
}

That statement is evaluated on your server. So, if the user doesn't have permission, the button will never be put on the page in the first place.

If you have JavaScript that the button relies on, you can hide that too by doing the same thing:

@if ([check if user has permission]) {
    <script>
        function doSomething() {
            //do something
        }
    </script>
}

A word of warning: if you do that inside of an already-existing <script> tag, you need to put the conditional JavaScript inside <text> tags so the Razor engine doesn't try to interpret the JavaScript:

<script>
    @if (true) {
        <text>
        function doSomething() {
            //do something
        }
        </text>
    }
</script>
Gabriel Luci
  • 38,328
  • 4
  • 55
  • 84