4

I've read some posts with some self implementations of this but I think now there should be some method in the ASP.NET MVC that should have this functionality.

I suppose there is some kind of method that can do what string.Format does:

 string.Format("example {0}", 1);

but instead of using {0} can work with variables names just like the MVC routes. for example:

 string.Format("example {id}", 1);

Is there such public method in ASP.NET MVC?

[Edit: Any idea how for example are action links rendered out of routes?]

1
  • This question is similar to: named String.Format, is it possible?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jun 30, 2024 at 15:25

2 Answers 2

1

As of C# language version 6.0 (VS2015 onwards) you can do this with Interpolated Strings (it's a compiler trick, so it doesn't matter which version of the .NET Framework you target).

The code then looks something like this

string txt = $"{person.ForeName} is not at home {person.Something}"; 

I think it makes the code more readable and less error prone, but it's not ideal if you want to put the strings into resource files for translation.

Sign up to request clarification or add additional context in comments.

Comments

0

No as of v2 preview 1, there is no such method in ASP.NET MVC. I don't know of any such method in the .NET Framework, either.

2 Comments

So how are action links rendered out of routes?
First, URI generation is part of the routing system, which is not part of MVC. The specific code is in System.Web.Routing.ParsedRoute.Bind, and can be read with Reflector, if you're interested. It is highly specific to URI generation and would not be useful for general string formatting.

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.