Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

Where is this ASP.NET feature documented? <%= string format, params object[] args %>

Apparently it is possible to write formatted output using the <%= %> construct (render block) in ASP.NET web forms pages and views.

<%= "{0} is {1}", "Foo", 42 %>

This will render "Foo is 42". As far as I know the ASP.NET parser translates <%= %> into a call to HttpResponse.Write(string). Obviously in the code above, there is no one-to-one translation, because the number of arguments don't match (assuming the , in the expression above separates arguments).

Now I have seen that the class TextWriter has a Write(string, object[]) method.

I have checked the output from the parser, and indeed it calls the TextWriter's method that accepts a params object[] argument for formatting:

private void @__Renderform1(System.Web.UI.HtmlTextWriter @__w, System.Web.UI.Control parameterContainer) {
    // ...
    @__w.Write( "{0} is {1}", "Foo", 42 );

Is that behavior documented anywhere?

Upvotes: 18

Views: 922

Answers (3)

dcaswell
dcaswell

Reputation: 3167

This is an <%= %> embedded code block and exists to maintain compatibility with Classic ASP.

As you saw <%= "{0} is {1}", "Foo", 42 %> is equivalent to:

string s = string.Format("{0} is {1}", "Foo", 42);
Response.Write(s);

That behavior is documented here:

Writes a formatted string that contains the text representation of an object array to the output stream, along with any pending tab spacing. This method uses the same semantics as the String.Format method. (Overrides TextWriter.Write(String, Object[]).)

Here is where it's documented that the Code Render Block calls the Write method.

Finally, the syntax for embedded code blocks has been updated for .NET 4 as described here.

Upvotes: 3

jbl
jbl

Reputation: 15413

As far as I know the ASP.NET parser translates <%= %> into a call to HttpResponse.Write(string).

Maybe the <%= "{0} is {1}", "Foo", 42 %> is translated to Response.Output.Write(string format, params object[] arg), Output being of type TextWriter, which would be the explanation according to http://www.hanselman.com/blog/ASPNETResponseWriteAndResponseOutputWriteKnowTheDifference.aspx

Upvotes: 3

guymid
guymid

Reputation: 1206

This is close and perhaps related http://msdn.microsoft.com/en-us/library/586y06yf.aspx but it's not an explanation for why the <%= does it...

Upvotes: -1

Related Questions