简体   繁体   English

在@Html.Raw 中输出 Razor 代码

[英]Output Razor code in @Html.Raw

I am trying to print a string in Razor using the following code:我正在尝试使用以下代码在 Razor 中打印一个字符串:

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

The output of this string is unfortunately: "Welcome @(ViewBag.Content.User.Name)!".不幸的是,这个字符串的输出是:“欢迎@(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.字符串的输出是:“Welcome Yanick!”,正是我想要的,但我不想这样打印。 Is there a possibility to run the Razor code that is inside a string (see first example)?是否有可能运行字符串内的 Razor 代码(参见第一个示例)? I tryed also Html.Encode() but this didn't work either...我也尝试过 Html.Encode() 但这也不起作用......

You can use C# version 6.0 feature, called string interpolation.您可以使用 C# 6.0 版功能,称为字符串插值。

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:如果您使用 C# 版本 < 6.0,则string.Format是您的选择:

@Html.Raw(string.Format("Welcome {0}!", ViewBag.Content.User.Name))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM