Search code examples
c#asp.net-mvcrazorseparation-of-concerns

When is it appropriate to create HTML code in the controller (or back end)


I am doing some complex logic involving loads of recursion to create a (complex) piece of HTML.

I started off doing this in the View using functions in Razor because I felt as HTML it belonged there.

But as it started getting more complex I thought I would rather do it in back-end code. Which it currently is.

It still feels a bit smellish though, and I am wondering if I should move it to the View again (which obviously clutters the view)

Which technically is more correct? When is it appropriate to use back-end code to generate HTML?

Thanks for your input.


Solution

  • Don't do it in controller. You can extend the HtmlHelper class and do the stuff there. For example if you are using a paging helper.

    Create a static class HtmlHelpers

    namespace YourMvcApplication.WebUI.HtmlHelpers
    {
        public static class PagingHelpers
        {
            public static MvcHtmlString PageLinks(this HtmlHelper html,int totalPages)
            {
                StringBuilder result = new StringBuilder();
                // do the complex logic to create dynamic html and append to 
                // String Builder
                return MvcHtmlString.Create(result.ToString());
            }
        }
    }
    

    Add reference to this class in all views in web.config.

    <namespaces>
        <add namespace="YourMvcApplication.WebUI.HtmlHelpers"/>
    </namespaces>
    

    Use and resuse this Html Helper methods wherever required.

    <div>
        @Html.PageLinks(Model.TotalPages)
    </div>