简体   繁体   中英

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?

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

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 .

这很接近并且可能与http://msdn.microsoft.com/en-us/library/586y06yf.aspx相关,但它不是为什么<%=这样做的解释...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM