Formatting Strings In ASP.NET

posted on 2005-09-18 at 00:46:35 by Joel Ross

There's an older post from Erik Porter about how he formats labels in ASP.NET. It's a pretty smart trick - he suggests that you use string placeholders for?labels, such as:

<asp:Literal id="MyLiteral" runat="server">Name: {0} {1}</asp:Literal>.

This way, you can just set the text using a String.Format() statement, rather than coding what the text will be in code. How does this help you? Well, as Erik points out, the HTML markup can be modifiied without recompiling, which is always a good thing. But Erik takes it one step farther - he mentions that a designer can modify the HTML, test it, and make the changes without needing a developer's help.

Is it just me, or wasn't this the promise of Visual Studio's (and ASP.NET's) code-behind model? That a designer can modify the .aspx file without needing to worry about the code behind the page? I think it was, but in practice, have you seen it happen? I've never had a designer on any project I've ever been on actually modify any production HTML page. Yes, they provide markup that I usually take and put into a page, but if updates are needed, it's always been up to a developer to make those changes. We never were able to maintain that break between designer and developer.

Of course, part of that is the fault of Visual Studio, and the way it handles a page and it's code-behind, especially with version control. Every time you check out a file, it checks out both the aspx and the code-behind. So much for only needing one! Combine that with the VS designer constantly screwing with both files at the same time, and you're never going to reach that separation.

Maybe the next Visual Studio will be better. Partial classes where you don't have to have a declaration for page components will help to prevent the designer needing both the page and the code-behind, and the new designer is supposed to be much less intrusive with HTML mangling, but we'll see. Regardless of those issues though, you still have to have a designer who understands the control syntax so they don't muck around too much!

Categories: ASP.NET