2

I thought that @ in Razor meant C# code. So, in a code like below I would not bother giving another @ before Html.Raw() because it is already wrapped in C# code:

@if (Session["User"] == null)
{
    Html.Raw("Welcome User <br>");
}

But turns out, the helper actually needs @ before it to signify its context as mentioned here otherwise it would not generate anything.

Can someone please explain why is that in more detail?

1
  • @user2864740 - good point... it should not be dup neither of "why @ used before string constant", nor "why @ used in identifiers"... I've edited sample to avoid one extra @. Dec 21, 2013 at 19:24

1 Answer 1

10

The other post explains exactly why you need the extra @ symbol in front of the Html.Row code.

Basically you can think about it like this:

  • the first @ in front of if states that the code in the if block is C# code and it will be parsed as such.

  • when the C# code is executed, Html.Raw(...) generates an MvcHtmlString object but you are not really doing anything with it. If you were writing pure code behind you would perhaps write some code to send the MvcHtmlString to the response output buffer or something similar

So, the second @ that you would need in front of Html.Raw(..) is actually a short-hand way of specifying that your want the result of the function to be be rendered in the output context, as opposed to be simply left dangling.

A different example might be helpful. This example is only indirectly related to your Razor question - regarding the concept of executing functions and discarding the result.

Let's say you have the following function definition:

  int Add(int a, int b)
  {
      return a + b;
  }

Now, you could call this function like this:

  Add(2, 3);

The code above would perform the addition, but the result will be discarded. You're not doing anything with it. Contrast that with:

  Console.WriteLine(Add(2, 3));    // now the result is being written to the console

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.