0

I am trying to print a string in Razor using the following code:

@Html.Raw("Welcome @(ViewBag.Content.User.Name)!")

The output of this string is unfortunately: "Welcome @(ViewBag.Content.User.Name)!". But when I print it this way:

@Html.Raw("Welcome " + @(ViewBag.Content.User.Name) + "!")

The output of the string is: "Welcome Yanick!", just what I want but I don't want to print it this way. Is there a possibility to run the Razor code that is inside a string (see first example)? I tryed also Html.Encode() but this didn't work either...

  • I don't think you can. The second line is fine, we all use it all the time, right? – Aleksandar Matic Oct 03 '16 at 13:11
  • Yeah, I know, but I saved it like the first string in the database. Just a simple editor that hardcoded saves that string... – Yanick van Barneveld Oct 03 '16 at 13:12
  • 2
    If the string is in the database as `"Welcome @(ViewBag.Content.User.Name)!"`, then the only thing you can do is manually run it through the Razor engine, first, before passing it to `@Html.Raw`. The parameter to `Html.Raw` is just a C# string, and Razor does not parse the contents of strings in code blocks. – Chris Pratt Oct 03 '16 at 13:14
  • 3
    Well... that's not a good practice. I would avoid saving parts of code in the database even if they could be executed later. That's very vulnerable. – Aleksandar Matic Oct 03 '16 at 13:16
  • You probably want http://stackoverflow.com/a/9661133/11683, although I believe you better rethink your approach. Also see http://stackoverflow.com/q/483091/11683. – GSerg Oct 03 '16 at 13:23
  • Possible duplicate of [Render string containing razor-code in view](http://stackoverflow.com/questions/35913730/render-string-containing-razor-code-in-view) – smoksnes Oct 03 '16 at 13:27
  • @YanickvanBarneveld You want to sanitize data before saving in database. It becomes ***garbage in, garbage out***. – Win Oct 03 '16 at 13:27

1 Answers1

0

You can use C# version 6.0 feature, called string interpolation.

In your case, it would be:

@Html.Raw($"Welcome {ViewBag.Content.User.Name}!")

If you're using C# version < 6.0, then string.Format is your choice:

@Html.Raw(string.Format("Welcome {0}!", ViewBag.Content.User.Name))
Yurii N.
  • 5,455
  • 12
  • 42
  • 66
  • If you have that level of control over the string, it's much better to just put it as literal html content. – GSerg Oct 03 '16 at 13:23
  • @GSerg that's question for author of the question, I don't know why he use `@Html.Raw` – Yurii N. Oct 03 '16 at 13:30