简体   繁体   English

如何从CSHTML.CS页面操作DOM?

[英]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. 我试图根据隐藏代码中用户的权限删除某些Web应用程序按钮。

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. 我试图触发javascript onload来删除指定的DOM元素,但是该页面将首先加载,然后在DOM之后将被修改。 I want the DOM to be modified first before the page even loads. 我希望在页面加载之前先修改DOM。

You're right in not wanting to rely on JavaScript for security, since any person knowledgeable in JavaScript can get around it. 您不希望依靠JavaScript来确保安全是正确的,因为任何精通JavaScript的人都可以解决它。

Use Razor syntax in your cshtml page to not even put it there in the first place. 在您的cshtml页面中使用Razor语法甚至不要将其放在首位。 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: 如果您具有按钮所依赖的JavaScript,则也可以通过执行相同的操作将其隐藏:

@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>标记内执行此操作,则需要将条件JavaScript放在<text>标记内,以便Razor引擎不会尝试解释JavaScript:

<script>
    @if (true) {
        <text>
        function doSomething() {
            //do something
        }
        </text>
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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