在 ASP.Net Gridview 中显示 Base64 字符串

Displaying Base64 String in ASP.Net Gridview

我的任务是使用 asp.net 显示信息,这需要我很容易实现的字符串字段,以及与信息一起显示的图像。我尝试在我的 gridview 中使用一个图像字段来显示一张图片,该图片适用于我有 url 的图像。但是,我一直在尝试找出一种方法来显示存储为 base64 字符串的图像。我尝试了各种方法来尝试显示图像,例如使用模板字段,尝试将图像 URL 设置为将在 html 中显示 base64 的字符串,甚至转换base64 到一个似乎不起作用的图像。现在我正在尝试使用数据表手动添加数据并手动创建行。如果有人知道我如何在图像视图中使用 base64 字符串,我将不胜感激。

这是我创建的网格视图的代码。

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#FF0000" HeaderStyle-ForeColor="White"
        runat="server" AutoGenerateColumns="false" enabled="false">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="30" />
            <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="30" />
            <asp:BoundField DataField="Account" HeaderText="Account Number" ItemStyle-Width="30" />
            <asp:ImageField DataImageURLField="ImageURL" HeaderText="Image" />
        </Columns>
</asp:GridView>

这是我现在拥有的用于在 gridview 中创建条目的 c# 代码。

DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Account",typeof(string)),
                        new DataColumn("ImageURL",typeof(string))});

        string URL = "data:image/jpg;base64,";

        string encodedString = //base64 string here


        URL += encodedString;

        dt.Rows.Add(1, "Steve", "************1111", URL);

        GridView1.DataSource = dt;
        GridView1.DataBind();

难以置信的 hacky,但它有效:

网格视图:

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#FF0000" HeaderStyle-ForeColor="White"
    DataSource='<%# GetData() %>' runat="server" AutoGenerateColumns="false" enabled="false">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="30" />
        <asp:BoundField DataField="Account" HeaderText="Account Number" ItemStyle-Width="30" />
        <asp:BoundField DataField="ImageURL" HeaderText="Image" HtmlEncode="false" />
    </Columns>
</asp:GridView>

代码隐藏:

public DataTable GetData()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)),
                new DataColumn("Name", typeof(string)),
                new DataColumn("Account",typeof(string)),
                new DataColumn("ImageURL",typeof(string))});

    string URL = "data:image/jpeg;base64,";

    string encodedString = ""; // base64-encoded image data goes here

    URL += encodedString;

    URL = $"<img src=\"{URL}\">";

    DataRow dr = dt.NewRow();

    dr["ID"] = 1;
    dr["Name"] = "Steve";
    dr["Account"] = "************1111";
    dr["ImageUrl"] = URL;

    dt.Rows.Add(dr);

    return dt;
}