Skindeep2366
Skindeep2366

Reputation: 1559

Formatting a table using Html helper function in MVC 3 Razor View

Using the following:

In my application I have a list(of string) that is sent to a view and is displayed. I am trying to have this display in a table format that is no more than 8 columns wide to many rows long. I have wrote a custom helper class to handle this but the view is showing the raw html code with the email addresses but its not rendering as a table with the rows and such.. Any ideas how to correct this.. Below is the helper class, the template, and finally the view.

Imports System.Runtime.CompilerServices
Public Module TableHelper
<Extension()> _
Public Function CreateEmailTable(ByVal helper As HtmlHelper, ByVal emaillist As List(Of String)) As MvcHtmlString
    Dim htmlDisplayer As String = Table()
    Dim counter As Integer = 0
    For Each item In emaillist
        If counter = 0 Then
            htmlDisplayer = htmlDisplayer + NRow()
        End If
        counter += 1
        If Not counter >= 8 Then
            htmlDisplayer = htmlDisplayer + Ntd(item)
        Else
            counter = 0
            htmlDisplayer = htmlDisplayer + CRow()
        End If
    Next
    htmlDisplayer = htmlDisplayer + CTable()
    Dim x As MvcHtmlString = MvcHtmlString.Create(htmlDisplayer)
    Return x
End Function
Public Function Table() As String
    Return String.Format("<table>")
End Function
Public Function CTable() As String
    Return String.Format("</table>")
End Function
Public Function NRow() As String
    Return String.Format("<tr>")
End Function
Public Function CRow() As String
    Return String.Format("</tr>")
End Function
Public Function Ntd(ByVal text As String) As String
    Return String.Format("<td>{0}</td>", text)
End Function
End Module

The Template View is:

@ModelTYPE List(Of String)
@Html.CreateEmailTable(Model)

And Finally the view is:

Modeltype xxxxxxxxx.EmailsVM
@Code
ViewData("Title") = "Mass Emails Sent"
End Code
@Using Html.BeginForm
@<fieldset>
<p>
@Html.Partial("_EmailsVM", Model.failEmList)
</p>
</fieldset>
End Using

And this is a snippet of what view page source is showing when I look at it in a browser:

  &lt;table&gt;&lt;tr&gt;&lt;td&gt;[email protected]; &lt;/td&gt;&lt;td&gt;[email protected]; &lt;/td&gt;&lt;td&gt;xxxxx.xxxxxxxx@xxxxx; &lt;/td&gt;&lt;td&gt; 

As can be seen its the html markup is losing its formating that browsers pick up on...

Upvotes: 0

Views: 2456

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65097

.NET strings are HTML encoded by default. You can either use Html.Raw() to print the raw HTML, or have it return an MvcHtmlString, which the MVC engine knows is already encoded and shouldn't encode again.

Reference: MvcHtmlString Class - MSDN

Upvotes: 1

Related Questions