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

CD..
  • 72,281
  • 25
  • 154
  • 163

3 Answers3

1

I don't know of a native way, but I think the solution lies with .NET 3.5 extension methods...

One blog shows a clever way to add string.format capabilities in an easier to read method.

And duh, I just found it. Take a look at this SO question. Brilliant!

Community
  • 1
  • 1
Michael La Voie
  • 27,772
  • 14
  • 72
  • 92
  • I mentioned I know there are some implementations of this, but based on the way MVC works with routes I thought there is some build-in method added in ASP.NET MVC. – CD.. Sep 15 '09 at 19:57
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.

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • So how are action links rendered out of routes? – CD.. Sep 15 '09 at 19:53
  • 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. – Craig Stuntz Sep 15 '09 at 20:23
0

As of Visual Studio 2015 you can do this with Interpolated Strings (its 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 its not ideal if you want to put the strings into resource files for translation, but

Sprotty
  • 5,676
  • 3
  • 33
  • 52