Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a textarea helper that takes content of the view as a parameter

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") %>
...
<% }) %>
like image 236
Omu Avatar asked Dec 17 '11 13:12

Omu


3 Answers

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.

like image 60
WiredPrairie Avatar answered Nov 13 '22 03:11

WiredPrairie


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")));
    }) %>
like image 23
imran_ku07 Avatar answered Nov 13 '22 03:11

imran_ku07


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")) %>
like image 23
Kalman Speier Avatar answered Nov 13 '22 04:11

Kalman Speier