How to html encode the output of an NHaml view (or any MVC view)?
- by jessegavin
I have several views written in NHaml that I would like to render as encoded html. Here's one.
%table.data
  %thead
    %tr
      %th Country Name
      %th ISO 2
      %th ISO 3
      %th ISO #
  %tbody
    - foreach(var c in ViewData.Model.Countries)
      %tr
        %td =c.Name
        %td =c.Alpha2
        %td =c.Alpha3
        %td =c.Number
I know that NHaml provides syntax to Html encode the output for given lines using &=. However, in order to encode the entire view, I would essentially lose the benefit of writing my view in NHaml since it would have to look like this....
&= "<table class='data'>
&= "  <thead>
So I was wondering if there was any cool way to be able to capture the rendered view as a string, then to html encode that string. Maybe something like the following???
public ContentResult HtmlTable(string format)
{
    var m = new CountryViewModel();
    m.Countries = _countryService.GetAll();
    // Somehow render the view and store it as a string?
    // Not sure how to achieve this.
    var viewHtml = View("HtmlTable", m); // ???
    return Content(viewHtml);
}
This question may actually have no particular relevance to the View engine that I am using I guess. Any help or thoughts would be appreciated.