【问题标题】:How to bind a html to a Gridview column?如何将 html 绑定到 Gridview 列?
【发布时间】:2014-02-24 03:00:17
【问题描述】:

我在谷歌上搜索了很多。但是,我没有得到任何线索。 提前感谢大家。

问题:我的数据表列中有一个 html 源。当它与我的 gridview 绑定时,我需要在我的 gridview 列中显示该 html 输出。这可能吗?

当前输出:

我的 aspx 代码:

 protected void Page_Load(object sender, EventArgs e)
 {
    DataTable dtEmployees = new DataTable();
    dtEmployees.Columns.Add(new DataColumn("FirstName", typeof(System.String)));
    dtEmployees.Columns.Add(new DataColumn("LastName", typeof(System.String)));
    dtEmployees.Columns.Add(new DataColumn("HomePhone", typeof(System.String)));
    dtEmployees.Columns.Add(new DataColumn("CellPhone", typeof(System.String)));
    dtEmployees.Columns.Add(new DataColumn("Address", typeof(System.String)));

    DataRow drEmpDetail = dtEmployees.NewRow();
    drEmpDetail["FirstName"] = "Tony";
    drEmpDetail["LastName"] = "Greg";
    drEmpDetail["HomePhone"] = "000-000-0000";
    drEmpDetail["CellPhone"] = "000-000-0000";
    drEmpDetail["Address"] = "Lane 1 Suite # 2 <br>";
  }

例如,在地址列中,我为“中断标记”提供了 html 标记。但在输出中它只是像字符串一样显示,结果与预期不符。

注意:我不想使用 Template 字段代替 BoundField。

【问题讨论】:

  • 你介意使用 jQuery 吗?

标签: c# gridview webforms


【解决方案1】:

尝试使用 - HttpUtility.HtmlDecode("Lane 1 Suite # 2 <br>")

标记将是,

<asp:TemplateField HeaderText="Address">
    <ItemTemplate>
        <%# HttpUtility.HtmlDecode(Eval("Address").ToString()) %>
    </ItemTemplate>
</asp:TemplateField> 

参考:http://msdn.microsoft.com/en-us/library/7c5fyk1k.aspx

【讨论】:

    【解决方案2】:

    这样设计你的gridview

    <asp:GridView runat="server" ID="gv1" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="FirstName"  DataField="FirstName" />
                <asp:BoundField HeaderText="LastName"  DataField="LastName" />
                <asp:BoundField HeaderText="HomePhone"  DataField="HomePhone" />
                <asp:BoundField HeaderText="CellPhone"  DataField="CellPhone" />
                <asp:BoundField HeaderText="Address"  DataField="Address" HtmlEncode="false" />
            </Columns>
        </asp:GridView>
    

    【讨论】:

      【解决方案3】:

      在您的 bounfield 属性中将 HtmlEncode 设置为 false

      <asp:BoundField HeaderText="Address" DataField="YourDataField" HtmlEncode="false" />
      

      BoundField HTML Encode Property MSDN

      【讨论】:

      • 这将是 HTML 输出。不@Damien,它不会是
      【解决方案4】:

      你可以使用 HttpUtility.HtmlDecode

      如果您使用的是 .NET 4.0+,您还可以使用 WebUtility.HtmlDecode,它不需要额外的程序集引用,因为它在 System.Net 命名空间中可用。

      【讨论】:

        猜你喜欢
        • 2014-07-29
        • 1970-01-01
        • 2017-09-02
        • 1970-01-01
        • 1970-01-01
        • 2011-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多