如何传递任何图像id

本文关键字:id 图像 任何 何传递 | 更新日期: 2023-09-27 18:04:56

尝试显示表中的最新图像,这里的代码工作正常,但无法显示最新图像,因为传入的图像url id被确定为image4。我希望图像id是任意id,并显示最新的图像。怎么做呢?

HTML:

<asp:image ToolTip = "ASP Image Control" ID="Image" runat="server" ImageUrl   ="Default.aspx?ImageID=4" Height="200px" Width="300px"></asp:image>

 if (Request.QueryString["ImageID"] != null)
    {
        string strQuery = "select TOP 1 Name, ContentType, Data from stock where id=@id order by id DESC";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32 (Request.QueryString["ImageID"]);
        DataTable dt = GetData(cmd);
        if (dt != null)
        {
            Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = dt.Rows[0]["ContentType"].ToString();
            Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        }
    }

如何传递任何图像id

如果你想获得最新的图像,你应该给Url传递空参数,而当你想获得特定的图像时,传递ID:

<asp:image ToolTip = "ASP Image Control" ID="Image" runat="server"
ImageUrl   ="Default.aspx?ImageID=" Height="200px" Width="300px"></asp:image>

和使代码依赖于ImageID值:

var imageIdParam = Request.QueryString["ImageID"];
if (imageIdParam != null)
{
    var imageId = imageIdParam == "" ? -1 : Convert.ToInt32 (imageIdParam);
    var cmd = new SqlCommand();
    var strQuery = "select TOP 1 Name, ContentType, Data from stock ";
    if(imageId > 0) {
        strQuery += "where id=@id ";
        cmd.Parameters.Add("@id", SqlDbType.Int).Value = imageId;
    }
    strQuery += "order by id DESC";
    cmd.CommandText = strQuery;
    DataTable dt = GetData(cmd);
    if (dt != null)
    {
        Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = dt.Rows[0]["ContentType"].ToString();
        Response.AddHeader("content-disposition", "attachment;filename=" + dt.Rows[0]["Name"].ToString());
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }
}

您可以在后面的代码中动态设置imageUrl。

int id = ...;
Image.ImageUrl = "Default.aspx?ImageID=+id;