5

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?

2
  • 1
    My first thought on this is, it's not a good idea. What you're saying is, that this resource string is tightly bound to razor only and cannot be used anywhere else. Additionally, it's now tightly bound to a run-time variable, meaning that it can only be debugged at run-time which can be very dangerous. Commented Oct 16, 2015 at 23:09
  • 1
    It's huge difference where you place your code.if you are inside Razor block (between @{ and }) then another @ is simply a syntactic error because you are already inside Razor. Then you need to use string.Format to format your string. On the other hand, if you inside HTML tag, @(variable) will work. Commented Oct 16, 2015 at 23:52

2 Answers 2

9

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))
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think that will work since the resource file variable isn't being referenced. I've updated the OP with that detail.
So writing @string.Format(MyManager.GetString("resourcefilevariable"), model.here); would not do the job?
That does work. I have some HTML in this resource file string (<strong> tag). It is coming through as a literal. Is there a way to make it render?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.