私を苛立たせ始めている問題があります。gridviews を使用して非常にシンプルなブログを作成しました。投稿に画像をアップロードできるという別の要件が与えられました。私が抱えている問題は、ユーザーが写真のない投稿を作成すると、画像コントロールに赤い x が表示されることです。私は成功せずに複数のことを試しました。投稿の画像を取得するためにカスタム ハンドラーを使用しています。
ImageHandler.ashx
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
dr.Read()
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
catch (Exception ex)
{
return;
}
}
Post テーブルに関連する Images テーブルがあります。ご覧のとおり、QueryString を使用して MessageID または Posts ID を取得し、画像を表示します。
これは、私が現在 Posts.aspx にイメージ コントロール用に持っているものです。
ASP
<asp:Image ID="postImage" runat="server" ImageUrl='<%# "ImageHandler.ashx?mid="+ Eval("MessageID") %>' Width="300px" Height="300px" GenerateEmptyAlternateText="True" />
こちらのソリューションとこちらのソリューションも試しましたが、何も成功しませんでした。Visible プロパティを使用して、「null」ではなく同じ結果の画像のみを表示しようとしました。他に何か必要なことがありましたら、お知らせください。
編集:これは、ImageHandler.ashx 用に私が持っているものです
ImageHandler.ashx
// 1x1 transparent GIF
private readonly byte[] GifData =
{
0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
0x02, 0x44, 0x01, 0x00, 0x3b
};
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboBlog"].ConnectionString);
public void ProcessRequest(HttpContext context)
{
try
{
string messageid = context.Request.QueryString["mid"];
conn.Open();
SqlCommand command = new SqlCommand("SELECT Image from BlogImages WHERE Image IS NOT NULL AND MessageID=" + messageid, conn);
SqlDataReader dr = command.ExecuteReader();
if (dr.Read())
{
context.Response.BinaryWrite((Byte[])dr[0]);
conn.Close();
context.Response.End();
}
else
{
context.Response.ContentType = "image/gif";
context.Response.Buffer = false;
context.Response.OutputStream.Write(GifData, 0, GifData.Length);
}
}
catch (Exception ex)
{
return;
}
}
Winの回答で提供されたこれを更新しました。これに関する唯一の問題は、グリッドビューに、各行が白とグレーの間で色が交互に変わるスタイルがあることです。したがって、画像がない場合に表示され、灰色の行にある白いボックスがあります。