如何使用MVC c#在运行时以字符串形式显示图像?

时间:2016-04-28 06:31:30

标签: c# asp.net-mvc

我从数据库中获取图像字节,并希望以字符串格式在图像src中呈现图像。如何在运行时呈现该图像? 这是我的情景。

public string GetTickerData()
        {
            string strData = "";
            string strImageData = "";
            string strDateFormat = "";
            byte[] imgdata;
            int s = 0;
            strImageData = "";                                   
            strImageData += "<img runat=\"server\" src=\"TickerImage.ashx?ColName=" + dtTickerData.Columns[j].ColumnName + "&ID=" + s + "\"  />";
            ViewData["Data"]=strImageData ;
        }

Image.cshtml

@{
  var t= @ViewData["Data"];
}
<div>
 <label class="footerLabel" style="text-align:center">@ViewData["Data"]</label>
</div>

图片处理程序

public class TickerImage : IHttpHandler
    {
        string ColumnName = string.Empty;
        int RowID = 0;
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["ColName"] != null)
                ColumnName = context.Request.QueryString["ColName"];

            if (context.Request.QueryString["ID"] != null)
                RowID = Convert.ToInt32(context.Request.QueryString["ID"]);
            else
                RowID = 0;

            DataTable dtTemp = (DataTable)context.Session["TickerData"];

            if (!(dtTemp.Rows[RowID][ColumnName] is DBNull))
                context.Response.BinaryWrite((byte[])dtTemp.Rows[RowID][ColumnName]);
        }


    }

1 个答案:

答案 0 :(得分:1)

看起来不错,但你错过了收尾报价。

strImageData += "<img src=\"" + imgg + "  />";

这应该是:

strImageData += "<img src=\"" + imgg + "\"  />";