0

I want to use Html.Razor in Html.Raw but it's not working.

For example:

var sourceString = "@var age = 25;@if(age > 20){<div>@age</div>}else{<div>@(age + 10)</div>}"

Html.Raw(sourceString)

Output : @var age = 25;@if(age > 20){<div>@age</div>}else{<div>@(age + 10)</div>}

But, I want to like this. -----> <div>25</div>

Do you have any idea?

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • Show the context, where and how do you use that code? – Poul Bak Jan 10 '22 at 15:13
  • @EmreCeylan: Solution doesn't trivial and described in this post: [Render string containing razor-code in view](https://stackoverflow.com/a/35914085/6630084) – Jackdaw Jan 11 '22 at 18:57

2 Answers2

0

Try to use rendering with the Razor <text> tag:

<html>
<body>
   <text>
       @{var age=25;if(age > 20){<div>@age</div>}else{<div>@(age + 10)</div>}}
    </text>
</body>
</html> 

Reference: Explicit delimited transition

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • It's didn't work for me. Because, i want to use C# code(if-else) in the string that I send into Html.Raw. Your string is ```
    Alice
    ``` but i sent ```
    {@firstName}
    ```
    – Emre Ceylan Jan 10 '22 at 15:59
  • @EmreCeylan: Update your question to clarify want exactly you want: add `if-else` etc. – Jackdaw Jan 10 '22 at 16:05
  • @EmreCeylan: I have updated the answer: See the **UPDATE**, please. Does this approach help to solve your problem? – Jackdaw Jan 10 '22 at 16:37
  • No, it doesn't fix it. I'm reading this string from a text file, so I cannot use razor at that time... – Emre Ceylan Jan 11 '22 at 07:36
  • @EmreCeylan: I have updated my answer with one more idea. Let me know if this can be used for your case. – Jackdaw Jan 11 '22 at 08:40
0

If you want the html to be <div>25</div>.You can use:

@{
    var age = 25;
    var sourceString=age>20?"<div>"+age+"</div>":"<div>"+(age+10)+"</div>";
}
@Html.Raw(sourceString)

result:

enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22