1

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?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • have a look to http://stackoverflow.com/questions/17419111/mixing-razor-syntax-with-javascript-in-views/17419419#17419419 – Kek Aug 01 '13 at 09:11
  • This is not a real question. _"What happens if..."_. **Try it**. You have the code in front of you, you can test it. StackOverflow isn't a crowdsourcing compiler. At the least, you can show you are willing to learn and trying to understand the problem. You could have done a search, where you would have found [how to use text tag in MVC 3 razor](http://stackoverflow.com/questions/4969065/how-to-use-text-tag-in-mvc-3-razor). – CodeCaster Aug 01 '13 at 09:18
  • if i write the code like this way then error occur ? @if (User.Identity.IsAuthenticated) { currentUser = '@User.Identity.Name'; } – Thomas Aug 01 '13 at 10:01

2 Answers2

1

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

Kek
  • 3,145
  • 2
  • 20
  • 26
1

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.