【问题标题】:Formatting a table using Html helper function in MVC 3 Razor View在 MVC 3 Razor View 中使用 Html 辅助函数格式化表格
【发布时间】:2012-08-10 07:27:28
【问题描述】:

使用以下内容:

  • MVC 3
  • VB.NET
  • RAZOR VIEW 引擎
  • HTML 帮助类

在我的应用程序中,我有一个发送到视图并显示的列表(字符串)。我正在尝试以不超过 8 列宽到多行长的表格格式进行显示。我已经编写了一个自定义帮助器类来处理这个问题,但是视图显示了带有电子邮件地址的原始 html 代码,但它没有呈现为带有行等的表格。任何解决此问题的想法。下面是帮助器类,模板,最后是视图。

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

模板视图是:

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

最后的观点是:

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

这是我在浏览器中查看时查看页面源代码的 sn-p:

  &lt;table&gt;&lt;tr&gt;&lt;td&gt;xxxxxxxxx@yahoo.com; &lt;/td&gt;&lt;td&gt;xxxxxxxx@xxxxxxx.net; &lt;/td&gt;&lt;td&gt;xxxxx.xxxxxxxx@xxxxx; &lt;/td&gt;&lt;td&gt; 

可以看出,它的 html 标记正在失去浏览器所接受的格式...

【问题讨论】:

    标签: asp.net-mvc vb.net asp.net-mvc-3 razor html-helper


    【解决方案1】:

    .NET 字符串默认为 HTML 编码。您可以使用 Html.Raw() 打印原始 HTML,或者让它返回一个 MvcHtmlString,MVC 引擎知道它已经编码并且不应该再次编码。

    参考:MvcHtmlString Class - MSDN

    【讨论】:

    • 非常感谢.. 当我意识到函数以字符串形式返回时,我开始着手解决这个问题。直到现在才知道 MvcHtmlString 类是什么...对于所有遇到的问题,我已经编辑了上面的辅助函数以显示有效的解决方案..
    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-04
    相关资源
    最近更新 更多