Mixing JavaScript and Razor syntax

2019-08-14 02:08发布

I was looking for how to mix razor and JavaScript together. I found something like this:

<script type="text/javascript">
var currentUser = null;
@if (User.Identity.IsAuthenticated) {
    <text>
        currentUser = '@User.Identity.Name';
    </text>
}
</script>

Why is the variable called currentUser surrounded with <text></text> tag? What is the meaning of <text> tag? If we omit that text tag then any error occur?

2条回答
smile是对你的礼貌
2楼-- · 2019-08-14 02:52

Well, this is how razor works. It uses brackets and tags begin/end to differenciate c# code from generated HTML

When you open a bracket, it it considered code until :

  • a corresponding closing bracket is encounterd
  • a tag is opened.

Then , opened tag will be considered html until a@ or correspoding closing tag is encountered. Sometimes, you want to switch from c# to HTML (or js) but you don't want to add a tag... then special tag id there for you. It is not rendered, just here to tell razor to switch rom C# to generated output

查看更多
Bombasti
3楼-- · 2019-08-14 02:56

The reason for the <text>…</text> tags is to solve the issue of ambiguities that arise as a result of your mixing two languages together that are semantically identical in many cases.

If you were to specify dynamic java script logic within the Razor syntax's C# if statements, and you had java script if statements in those blocks, how would it differentiate the context between the two?

The problem is: it can't; odds are, programmers can't either. The <text>…</text> tag is a special Razor block (inside C# blocks only) style escape that says: this is definitely (probably) not C# code that is in this block.

Things get a bit dicey when you realize you can then add another escape inside the <text>…</text> block. Like anything though you would use it with caution. If you're having a lot of trouble mixing the two and can't figure out where to add your text blocks, odds are you shouldn't be using it (in production) until you understand it better.

查看更多
登录 后发表回答