Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does putting @ before Html.Raw work?

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?

like image 925
lbrahim Avatar asked Apr 10 '26 09:04

lbrahim


1 Answers

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
like image 200
Mike Dinescu Avatar answered Apr 12 '26 21:04

Mike Dinescu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!