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?

3
  • have a look to stackoverflow.com/questions/17419111/… Commented Aug 1, 2013 at 9: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. Commented Aug 1, 2013 at 9:18
  • if i write the code like this way then error occur ? @if (User.Identity.IsAuthenticated) { currentUser = '@User.Identity.Name'; } Commented Aug 1, 2013 at 10:01

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.