开发者

Is there a better, less cumbersome way to extract text inline than <%= %>?

Let's say I am working in a .aspx page (or View, for the MVC folk) and I have a block of inline code:

<p>Some HTML and content</p>

<% foreach (var x in foo) { %>
   <%= x.myProperty %>
<% } %>

<p>Moar HTMLz</p>

Is there a more efficient, less cumbersome way to extract text into the markup than this model? It seems like there are a l开发者_如何转开发ot of <%'s

EDIT I guess what I'm really asking is if there's any better way to get text on the page from a codeblock without leaving the code block, re-entering into a code block, and then reentering the enclosing codeblock.


If the goal is strictly to have fewer <% %> sections, you can write it out the long way, but that's hardly an improvement:

<% foreach (var x in foo) {
       Response.Write(Html.Encode(x.MyProperty));
   } %>

If you just want to keep it out of the aspx page, you could move it to a control:

<% Html.RenderPartial("properties", foo); %>

One advantage of this technique is that you could utilize a different view engine (say, NHaml) for the partial while still keeping the general structure of your aspx page (view) in tact.


Create an extension method for enumerable collections:

public static void Each<T>(this IEnumerable<T> list, Action<T> fn)
{
          foreach (T item in list)
        fn(item);
}

And then do:

foo.Each((i) => Response.Write(Html.Encode(x.MyProperty)));

Or, to make it even easer, use a custom view page (for MVC) or custom page class (for Web forms) that has a method that does this already for you:

public void WriteText(string coreText)
{
    Response.Write(Html.Encode(coreText));
}

To make it even easier. Extension methods really help with that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜