asp.net mvc - mvc4 htmlhelper extension to store block of html for later output in same file -


ok, here's i'm trying do... given razor code

@using(html.writelater()) {     output line 1 } actual first line @using(html.writelater()) {     output line 2 } actual second line  @html.writenow(); 

i want output:

actual first line actual second line output line 1 output line 2 

there times when nice logically group blocks of code in view, final output needs organized differently. i've tried ataching different viewcontext in helper logic doesn't work:

public static writelatercontainer writelater( htmlhelper htmlhelper ) {     viewcontext vc = new viewcontext();     return new writelatercontainer( vc ); } 

no idea why want reinvent wheels instead of using standard approaches such partials, sections, helpers, ... guess have reasons. not syntax have shown achieve similar results using conjunction of 2 helpers:

public static class htmlextensions {     private const string queuekey = "_output_queue_";     public static ihtmlstring writelater(this htmlhelper htmlhelper, func<object, helperresult> action)     {         var queue = htmlhelper.viewcontext.httpcontext.items[queuekey] queue<func<object, helperresult>>;         if (queue == null)         {             queue = new queue<func<object, helperresult>>();             htmlhelper.viewcontext.httpcontext.items[queuekey] = queue;         }         queue.enqueue(action);          return mvchtmlstring.empty;     }      public static ihtmlstring writenow(this htmlhelper htmlhelper)     {         var queue = htmlhelper.viewcontext.httpcontext.items[queuekey] queue<func<object, helperresult>>;         if (queue == null)         {             return mvchtmlstring.empty;         }          var writer = htmlhelper.viewcontext.writer;         foreach (var item in queue)         {             item(null).writeto(writer);         }          return mvchtmlstring.empty;     } } 

that used this:

@html.writelater(@<div>output line one</div>) <div>actual first line</div> @html.writelater(@<div>output line two</div>) <div>actual second line</div> @html.writenow() 

and output expected one:

actual first line actual second line output line 1 output line 2 

Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -