Search code examples
c#asp.net-mvcrazorrazorengine

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?


Solution

  • 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))