I'm not even sure if this is possible, but I thought I would check to see if there is any way to make this easier.
First, I have some repeated markup in my site that looks like this:
<div class="module">
<h3>Title</h3>
<div>
<p>Information goes here</p>
</div>
</div>
What I want to do is wrap this up in some kind of helper/section so that I could do something like this
@MyHelper("This is my Title") {
<p>Here is my custom markup</p>
}
Then, when it renders, it would inject the title passed in through the parameter between the <h3></h3>
and the custom markup in the divs. The custom markup could be anything from test, to form controls, to a partial view. Is this something that is possible?
Well, here's a "standard" way of doing something close to it, using an HTML helper extension. A very simple version of what
Html.BeginForm()
does.Approach: Simply return an IDisposable, and let the
using
statement take care of the rest.This is just an example of the concept (although it works). Not intended for immediate reuse. Written quickly with lots of shortcuts, not production code, plenty of opportunities for improvement and optimization, may have silly mistakes, could use TagBuilder etc. etc. Could easily be modified to reuse the Wrapper class for different... wrappings (there may even be a generic one already in ASP.NET MVC - haven't had a need for one).
Usage:
If you are using Razor and MVC 3 it's real easy to write a quick helper method that would go inside the app_code folder, (I'll name it MyHtmlHelpers)
I'd try something a little different and a little easier such as:
And the way you use it from a .cshtml file is as followed:
It should work, if I understand you correctly.
@TheKaneda, Thanks for the insight. I took your idea and extended it, such that you supply a PartialView name and it knows how to parse it.
Use the same usage as @TheKaneda's example. In your partial view, instead of calling @RenderBody(), just put @@RenderBody() which acts as a flag for the middle part of your content. Sorry for the VB translation.
Uses an example of my usage.
My Partial looks like this...
There's also the other way, without disposable trick, which also requires a little less work, great for little helpers.
Usage of this helper looks like this:
Or with multiple lines:
Telerik MVC controls used this trick for example to let you add your javascript code at the document load.
Here's also a nice example. There's also some information here.