简体   繁体   English

如何在字符串中嵌入剃须刀变量?

[英]How to embed razor variable in string?

I'd like to add a razor model variable into a resource file string. 我想将剃刀模型变量添加到资源文件字符串中。 I've tried the following but the variable is rendered as a literal: 我已经尝试了以下方法,但是变量呈现为文字:

attempt 1: 尝试1:

"There is a variable @Model.here"

attempt 2: 尝试2:

"There is a variable @(Model.here)"

In the code, it is referenced like this: 在代码中,引用如下:

@MyManager.GetString("resourcefilevariable")

Is there some way to do this? 有什么办法可以做到这一点?

It is better to do this kind of thing by storing 最好通过存储来做这种事情

"There is a variable {0}"

as the resource string, and in the view, writing something like this: 作为资源字符串,并在视图中编写如下内容:

@string.Format(Resources.String, model.here);

As a full example: 举一个完整的例子:

Here is the model class: 这是模型类:

public class Foo
{
    public string Name { get; set; }

    public Foo()
    {
        Name = "bar";
    }
}

It has controller with a simple Index ActionResult: 它具有带有简单Index ActionResult的控制器:

    // GET: Foo
    public ActionResult Index()
    {
        return View(new Foo());
    }

There is a resx file with resource 有一个带有资源的resx文件

[resourceName, <strong>name of model is: {0}</strong>]

In the razor view, render this as 在剃刀视图中,将其渲染为

@Html.Raw(string.Format(Resources.resourceName, Model.Name))

As Leigh Shepperson pointed out, you can use a string with placeholders and string.Format to replace placeholders with actual values. 正如Leigh Shepperson指出的那样,您可以使用带占位符的字符串和string.Format来将占位符替换为实际值。 If the string contains any HTML tags it should be rendered with Html.Raw method. 如果字符串包含任何HTML标记,则应使用Html.Raw方法呈现。

@Html.Raw(string.Format(Resources.String, model.here))

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

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