I would like to create a html helper that would receive as a parameter content of the view, like this:
<% Html.MyTextArea("txt1", () => {%>
content of the view
<%=Html.TextBox("Name") %>
...
<% }) %>
Since you've tagged it as MVC, I'm going to propose you could do something like I posted on my blog as a way to get syntax highlighting for templates as the solution would be very similar, IF you don't need to manipulate the inner content and are simply interested in 'wrapping' it in some way (like in a containing element that requires some extra logic).
Using the technique, the HtmlHelper method receives the context of the block. The syntax is slightly different from your suggested technique though.
For example, you could have something like:
@using(Html.MyTextArea("txt1"))
{
<some HTML content here>
}
The context is passed to an IDisposable object which includes a Writer (for writing to the current output stream). There, it can output multiple elements or do other manipulation as needed. The Dispose is used to write a close element (if needed).
So, you could end up with something like this:
<textarea><some HTML content here></textarea>
However, as I mentioned this does not provide the inner content to the function itself.
As Razor pages render inside out, there's not an effective method to grab the output in the way you're wanting. There are some posts around about caching the output of a Partial to a string (which would mean the inner content in your example would be in another file, an .ascx file), so you might want to look at those.
One approach is,
public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, Action<TextWriter> action)
{
var writer = new StringWriter();
action(writer);
// here writer contains the html
return htmlHelper.TextArea(name);
}
<%:Html.TextArea("txt1",(writer) => {
writer.Write("content of the view");
writer.Write(HttpUtility.HtmlEncode(Html.TextBox("Name")));
}) %>
Do you mean something like this?
namespace System.Web.Mvc {
public static class HtmlHelperExtensions {
public static MvcHtmlString MyTextArea(this HtmlHelper htmlHelper, string id, Func<MvcHtmlString> helperFunc) {
return new MvcHtmlString(string.Format("<div id=\"{0}\">{1}</div>", id, helperFunc()));
}
}
}
You can use this way:
<%: Html.MyTextArea("txt1", () => Html.TextBox("Name", "abc")) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With