Quantcast
Channel: C1 CMS Foundation - Open Source on .NET
Viewing all articles
Browse latest Browse all 2540

New Post: Razor Html Helpers

$
0
0
This is not a question, but a reference for anyone else who might struggle with the same issue.

I wanted to create my own HtmlHelper extension method for output an optional div wrapper for some content that can be called like this:
using (Html.OptionalWrapper("<div class=\"optional-wrapper\">", "</div>", shouldOutputWrapper))
{
    <p>This paragraph will be wrapped with a div if 'shouldOutputWrapper' is true</p>
}
I had great difficulty because the razor functions are using System.Web.WebPages.Html.HtmlHelper instead of System.Web.Mvc.HtmlHelper. In the former, you can't get a handle on the ViewContext to access the HtmlWriter, which is necessary for performing such a task.

After searching through the c1 codebase, in the end I worked out how to do it, and thought I'd share the Extension method I'm using in case anyone else wants to do something similar.
namespace MvcHelpers
{
    public static class HtmlExtensions
    {
        private class OptionalWrapperCloser : IDisposable
        {
            private readonly TextWriter writer;
            private readonly string closingTag;
            private readonly bool test;

            public OptionalWrapperCloser(TextWriter writer, string closingTag, bool test)
            {
                this.writer = writer;
                this.closingTag = closingTag;
                this.test = test;
            }

            public void Dispose()
            {
                if (test) writer.Write(closingTag);
            }
        }

        public static IDisposable OptionalWrapper(this HtmlHelper html, string openingTag, string closingTag, bool test)
        {
            var page = (WebPageBase) WebPageContext.Current.Page;
            var writer = page.Output;
            if (test) writer.Write(openingTag);
            return new OptionalWrapperCloser(writer, closingTag, test);
        }

    }
}
The key lines of code that get a handle on the necessary HtmlWriter are:
var page = (WebPageBase) WebPageContext.Current.Page;
var writer = page.Output;

Viewing all articles
Browse latest Browse all 2540

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>