views:

96

answers:

2

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 lot 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.

+3  A: 

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.

nullptr
yeah, but even if i pull it out and put it in a control, i still have to do the same thing. the question is, if i want to get simple text from a codeblock onto the page, is there another method other than `<%= %>`
Jason
+2  A: 

Hey,

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.

Brian
but does this detract from the fact that you still need 3 sets of `<%= %>`?
Jason
All you would need is:<% foo.Each((i) => Response.Write(Html.Encode(x.MyProperty))); %>One set of <% %> is all you would need then. It get's all of that processing into one statement too, reducing the overall amount of code (especially if you do this operation a lot).Other than aestetics, I'm not sure why you want to avoid several script blocks... it doesn't reduce performance...
Brian