views:

96

answers:

1

I thought of a neat hack this morning, probably not original, but I haven't seen it before. I don't consider it good practice, but can help when you need to render a block of code repeatedly around your page, and don't want to touch other code or create other files (partial views or components).

In your .aspx file create an anonymous delegate like so:

<%
Action<DataType> renderMe = data => {
  %> Some html text <a href="<%= data.url %>">That can</a> contain quotes, etc. 
     And other <%= data.something %> stuff...
  <%
};
%>

Then you can simply use it anywhere you want: (myvar1 and myvar2 are of type DataType)

This is some html and I want the block here: <% renderMe(myvar1); %> ...
or maybe here <% renderMe(myvar2); %>

I know it's not a great idea, but can anyone see any problems with doing this?

A: 

This ain't bad per se. Quite similar to Spark's macros (that looks better imho). Rashud`s script manager (for advanced js initialization) uses the same technique. MvcContrib's grid renderer does the same too.

Thing is - niche when this is suitable is really narrow. Only when desired snippet of html should be passed to server side or when you want to re-use it twice or more in context of one specific view but don't want to create separate partial view.

Arnis L.