简体   繁体   中英

How do I manipulate the DOM from the CSHTML.CS page?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM