Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

"There is a variable @Model.here"

attempt 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?

like image 845
4thSpace Avatar asked Oct 16 '15 22:10

4thSpace


2 Answers

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:

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

There is a resx file with resource

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

In the razor view, render this as

@Html.Raw(string.Format(Resources.resourceName, Model.Name))
like image 91
Leigh Shepperson Avatar answered Oct 04 '22 19:10

Leigh Shepperson


As Leigh Shepperson pointed out, you can use a string with placeholders and string.Format to replace placeholders with actual values. If the string contains any HTML tags it should be rendered with Html.Raw method.

@Html.Raw(string.Format(Resources.String, model.here))
like image 31
Lukas Kabrt Avatar answered Oct 04 '22 18:10

Lukas Kabrt