0

I have a string I'd like to format in a javascript function on a Razor page. I am currently doing it by concatenating the sub strings.

function Foo(actionName, entityName) {
    var message = "Are you sure you want to ".concat(actionName).concat(" ").concat(entityName);
}

I would like to be able to call C# directly to concatenate the substrings more cleanly with something like this:

@var message = $"Are you sure you want to {actionName} {entityName}";

How do I do this with embedded C# in the Razor page javascript?

2 Answers 2

3

In JavaScript, it's possible to format strings using template literals.

An example from Mozilla's documentation would be:

console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
Sign up to request clarification or add additional context in comments.

Comments

0
function Foo(actionName, entityName) {
    var message = "Are you sure you want to "+ actionName + " " + entityName;
    console.log(message);
}

//or this
function Foo(actionName, entityName) {
    var message = 'Are you sure you want to '+ actionName + ' ' + entityName;
    console.log(message);
}
//or this
function Foo(actionName, entityName) {
    var message = `Are you sure you want to `+ actionName + ` ` + entityName;
    console.log(message);
}
//or this
function Foo(actionName, entityName) {
    var message = [`Are you sure you want to `,actionName,entityName].join(` `);//feel free to use `` or '' or ""
    console.log(message);
}

4 Comments

I don't think this is what the OP had in mind.
@RobertHarvey you have a point. Julian Goldsmith has already given the answer I would I have given. I thought I should add this for completeness. This I think is still cleaner than the one in the question.
I'm new to Razor and was looking at using the embedded C# features.
Specifically, I'd like to user something like to be able to define on a Razor page, a string like this $"{personName} has a {petTypeName}"

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.